程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Filestream讀取或寫入文件,filestream讀取寫入

Filestream讀取或寫入文件,filestream讀取寫入

編輯:C#入門知識

Filestream讀取或寫入文件,filestream讀取寫入


 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 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved