我的新浪博客 我的视频制作室 我的QQ空间

点滴积累【C#】---操作文件

操作文件

写入文件效果:

  

写入文件代码:

 1 private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5                 FileStream fs = new FileStream(@"D:\FileStream.txt", FileMode.Create);
 6                 StreamWriter sw = new StreamWriter(fs);
 7                 string content = textBox1.Text.Trim();
 8                 sw.Write(content);
 9                 sw.Close();
10                 fs.Close();
11                 MessageBox.Show("保存成功");
12             }
13             catch
14             {
15                 MessageBox.Show("保存出错");
16             }
17         }

 


 

读取文件效果:

 

读取文件代码:

 1 private void 查看ToolStripMenuItem_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5                 FileStream fs = new FileStream(@"D:FileStream.txt", FileMode.Open);
 6                 StreamReader sr = new StreamReader(fs);
 7                 string content = sr.ReadToEnd();
 8                 textBox1.Text = content;
 9                 sr.Close();
10                 fs.Close();
11 
12             }
13             catch
14             {
15                 MessageBox.Show("查看出错");
16             }
17             
18         }

 


 

拷贝文件效果:

 

拷贝文件代码:

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5                 string path1 = textBox1.Text.Trim();
 6                 string path2 = textBox2.Text.Trim();
 7                 if (File.Exists(path1) == true)
 8                 {
 9                     File.Copy(path1, path2);
10                     MessageBox.Show("拷贝成功");
11                 }
12             }
13             catch
14             {
15                 MessageBox.Show("拷贝失败");
16             }
17         }

 

移动文件:

 

代码:

 1 private void button2_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5                 string path1 = textBox1.Text.Trim();
 6                 string path2 = textBox2.Text.Trim();
 7                 if (File.Exists(path1) == true)
 8                 {
 9                     File.Move(path1, path2);
10                     MessageBox.Show("移动成功");
11                 }
12             }
13             catch
14             {
15                 MessageBox.Show("移动失败");
16             }
17         }

删除文件

代码:

 1 private void button3_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5                 string path = textBox1.Text.Trim();
 6                 if (File.Exists(path) == true)
 7                 {
 8                     File.Delete(path);
 9                     MessageBox.Show("删除成功");
10                 }
11             }
12             catch
13             {
14                 MessageBox.Show("删除失败");
15             }
16         }

 

posted @ 2013-11-21 21:33  青苹果  阅读(225)  评论(0编辑  收藏  举报