Document | Personal Blog

Document

1.例如说我们要创建一个文件修改界面,需求大体上应该是什么样的?

a.实现文件的抓取
b.实现文件的更改
c.实现文件的创建
d.实现文件的读入

2.逐一分析需求

首先,需要找到这个文件。
我们可以通过路径来唯一确定文件在系统中的位置
现在就产生了两种方法:

1st 用户直接输入路径,较为麻烦
2nd 提供窗口来逐层寻找文件位置

然后,找到了这个文件,接下来需要对文件进行读取
将文件内容提取到一个文本框中
对文本框内的内容进行修改,并储存到文件中

3.代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
        using System;  
        using System.Collections.Generic;  
        using System.ComponentModel;  
        using System.Data;  
        using System.Drawing;  
        using System.Linq;  
        using System.Text;  
        using System.Threading.Tasks;  
        using System.Windows.Forms;  
        using System.IO;`

        namespace A._4._2  
        {  
            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();
                }


                private void button2_Click(object sender, EventArgs e)//如果读取文件按钮被按下
                {
                    if (textBox2.Text != null)                        //路径输入框须有内容
                    {

                        string path;
                        path = Convert.ToString(textBox2.Text);       //读取输入框内容
                        if (File.Exists(path))
                        {
                            StreamReader sr = File.OpenText(@path);   //StreamReader类,操纵字符//@的意思是后面的“/”符号失去转义效果
                            string str = sr.ReadToEnd();              //一键读取所有文件内容
                            textBox1.Text = str;
                            sr.Close();                               //最后要记得关掉文件
                        }
                        else
                        {
                            MessageBox.Show("文件不存在!");
                        }
                    }

                }

                private void button3_Click(object sender, EventArgs e)//文件存储选项
                {
                    File.WriteAllText(@textBox2.Text, textBox1.Text);
                }

                private void button1_Click(object sender, EventArgs e)//文件浏览选项弹窗
                {
                    OpenFileDialog open = new OpenFileDialog();
                    if (open.ShowDialog() == DialogResult.OK)         //通过确认按钮发送路径
                    {
                        textBox2.Text = open.FileName;                //将抓取到的路径放到输入框
                    }
                }
            }
        }