如果是操作文本檔案類型
推薦使用: StreamReader、StreamWriter
示例:StreamWriter 用于寫入,可以使用 WriteLine(xxx) 函數将内容寫入指定檔案當中
1 try
2 {
3 //StreamWriter用于将内容寫入文本檔案中
4 //path: 要寫入檔案的路徑
5 //append: true 将資料追加到該檔案的末尾; false 覆寫該檔案。
6 //Encoding.UTF8 寫入的編碼格式
7 //如果指定的檔案不存在,構造函數将建立一個新檔案。
8 using (StreamWriter sw = new StreamWriter(@"D:\aaa.txt", true, Encoding.UTF8))
9 {
10 sw.WriteLine("我是老大");
11 sw.WriteLine("我是老三");
12 sw.WriteLine("我是老四");
13 sw.WriteLine("我是老五");
14 sw.Close();
15 }
16 Console.WriteLine("寫入成功了。。。");
17 }
18 catch (Exception ex)
19 {
20 Console.WriteLine(ex.Message);
21 }
如果檔案不存在,會自動建立。

StreamReader 用于讀取,ReadLine 表示一行行讀取,還有其他讀取方法,具體到程式集檢視即可
1 //StreamReader用法
2 try
3 {
4 using (StreamReader sr = new StreamReader(@"D:\aaa.txt", Encoding.UTF8))
5 {
6 while (true)
7 {
8 var str = sr.ReadLine(); //一行行的讀取
9 if (str == null) //讀到最後會傳回null
10 {
11 break;
12 }
13 Console.WriteLine(str);
14 }
15 sr.Close();
16 }
17 Console.WriteLine("讀取結束了。。。");
18 }
19 catch (Exception ex)
20 {
21 Console.WriteLine(ex.Message);
22 }
如果是操作 其他類型的檔案(包括文本檔案),可以使用 FileStream,
比如我們操作一張圖檔檔案
1 //FileStream 用法 讀取檔案
2 try
3 {
4 //FileMode.OpenOrCreate 表示檔案不存在,會建立一個新檔案,存在會打開
5 using (Stream fs = new FileStream(@"D:\123.jpg", FileMode.OpenOrCreate))
6 {
7 byte[] bt = new byte[fs.Length]; //聲明存放位元組的數組
8 while (true)
9 {
10 var num = fs.Read(bt, 0, bt.Length); //将流以byte形式讀取到byte[]中
11 if (num <= 0)
12 {
13 break;
14 }
15 }
16 fs.Close();
17
18
19 //将 123.jpg 檔案中讀到byte[]中,然後寫入到 456.jpg
20 //FileAccess.ReadWrite 表示支援讀和寫操作
21 using (Stream fs2 = new FileStream(@"D:\456.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite))
22 {
23 //設定位元組流的追加位置從檔案的末尾開始,如果檔案不存在,隻預設0開始
24 fs2.Position = fs2.Length;
25
26 //将待寫入内容追加到檔案末尾
27 fs2.Write(bt, 0, bt.Length);
28
29 //關閉
30 fs2.Close();
31 }
32 }
33 }
34 catch (Exception ex)
35 {
36 Console.WriteLine(ex.Message);
37 }
生成效果如下
作者:PeterZhang
出處:https://www.cnblogs.com/peterzhang123
本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,并保留此段聲明,否則保留追究法律責任的權利。