文件操作

1.文件操作

  1.1文件创建

  

  点击Create按钮就会在路径上创建文件

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             if (textBox1.Text != "")
 4             {
 5                 if (!File.Exists(textBox1.Text))  //路径有无重名文件
 6                 {
 7                     try
 8                     {
 9                         FileStream fs = File.Create(textBox1.Text);
10                         MessageBox.Show("Yes");
11                     }
12                     catch (Exception ex)
13                     {
14                         MessageBox.Show(ex.Message);
15                     }
16                 }
17                 else
18                     MessageBox.Show("Please Input");
19             }
20         }

 

  1.2写入文件

  

 1  private void button1_Click(object sender, EventArgs e)
 2         {
 3             FileStream fs;
 4             try
 5             {
 6                 fs = File.Create(textBox1.Text); //创建文件并且返回FileStream对象
 7             }
 8             catch (Exception ex)
 9             {
10                 MessageBox.Show("Error");
11             }
12             byte[] content = new UTF8Encoding(true).GetBytes(textBox2.Text);//将文本内容存在数组中
13             try
14             {
15                 fs.Write(content, 0, content.Length); //写入文件
16                 fs.Flush();//清空缓存区
17                 MessageBox.Show("yes", "save", MessageBoxButtons.OK, MessageBoxIcon.Information);
18             }
19             catch (Exception ex)
20             {
21                 MessageBox.Show(ex.Message);
22             }
23             finally
24             {
25                 fs.Close();  //关闭流
26             }
27         }

  File类位于System.IO命名空间, 包含处理文件的静态方法, 可以通过Create方法返回一个FileStream对象  

  Encoding.GetBytes()方法将所有编码为一个字节序列

 

  1.3读取文件信息

  

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             OpenFileDialog file = new OpenFileDialog();
 4             if (file.ShowDialog() == DialogResult.OK)
 5             {
 6                 textBox1.Text = file.FileName;
 7             }
 8         }
 9 
10         private void button2_Click(object sender, EventArgs e)
11         {
12             try
13             {
14                 if (!File.Exists(textBox1.Text))
15                 {
16                     MessageBox.Show("Not Existed");
17                 }
18                 else
19                 {
20                     FileStream fs = File.OpenRead(textBox1.Text);
21                     byte[] arr = new byte[100];
22                     UTF8Encoding data = new UTF8Encoding(true);
23                     while (fs.Read(arr, 0, arr.Length) > 0)
24                         textBox2.Text = data.GetString(arr);
25                 }
26             }
27             catch (Exception ex)
28             {
29                 MessageBox.Show(ex.Message);
30             }
31         }

 

  

posted @ 2014-07-22 21:38  Mirrorhanman  阅读(172)  评论(0编辑  收藏  举报