1. 程式人生 > 實用技巧 >IO檔案讀寫操作

IO檔案讀寫操作

如果是操作文字檔案型別

推薦使用: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 }

生成效果如下