1 using System.IO;//引用 System.IO
2 namespace filestream
3 {
4 public partial class Form1 : Form
5 {
6 public Form1()
7 {
8 InitializeComponent();
9 }
10
11 private void btnWrite_Click(object sender, EventArgs e)
12 {
13 SaveFileDialog sfd = new SaveFileDialog();
14
15 sfd.Filter = "文本文件|*.txt|c#文件|*.cs";
16
17 if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
18 {
19 txtPath.Text = sfd.FileName;//保存的路径
20 using (FileStream fs = new FileStream(txtPath.Text, FileMode.Create))
21 {
22 string txt = txtContent.Text;
23 byte[] buffer = Encoding.UTF8.GetBytes(txt);
24 fs.Write(buffer, 0, buffer.Length);
25 }
26 }
27 }
28
29 private void btnRead_Click(object sender, EventArgs e)
30 {
31 OpenFileDialog ofd = new OpenFileDialog();
32 ofd.Filter = "文本文件|*.txt";
33 if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
34 {
35 txtPath.Text = ofd.FileName;
36 using (FileStream fs = new FileStream(txtPath.Text, FileMode.Open))
37 {
38 //byte[] buffer = new byte[fs.Length];
39 //fs.Read(buffer, 0, buffer.Length);
40
41 //string msg = Encoding.UTF8.GetString(buffer);
42 //txtContent.Text = msg;
43
44
45 using (StreamReader sr = new StreamReader(fs,Encoding.UTF8))
46 {
47 string msg = sr.ReadToEnd();
48 txtContent.Text = msg;
49 }
50 }
51 }
52 }
53 }
54 }