首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# StreamReader/StreamWriter 文字檔讀寫實戰指南

     編輯:關於C#

FileStream 僅支援位元組層級操作,處理文字檔需自行編解碼。StreamReader/StreamWriter 封裝字元編碼與緩衝,提供以行、字元、字串為單位的高階文字讀寫 API,是文字檔處理的首選工具。

一、StreamReader 讀取文字檔

常用建構子

// 從 FileStream 建立(可控制 FileMode/FileAccess)
FileStream fs = new FileStream(@"c:\abc.txt", FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs); // 預設 UTF-8

// 直接指定路徑建立(最常用)
StreamReader sr2 = new StreamReader(@"c:\abc.txt");

支援指定 Encoding、detectEncodingFromByteOrderMarks、bufferSize、leaveOpen 等進階選項。

逐行讀取標準模式

FileStream fs = new FileStream(@"c:\abc.txt", FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);

string line = sr.ReadLine(); // 讀取一行(不含換行符)
while (line != null)
{
    Console.WriteLine(line);
    line = sr.ReadLine();
}

sr.Close();  // 關閉 Reader(若 leaveOpen=false 也會關閉底層 Stream)
fs.Close();  // 確保釋放檔案鎖定

輸出結果:主控台逐行顯示檔案內容,與檔案原文完全一致。

其他讀取方法

  • Read():讀單一字元,回傳 int(-1 表結束)
  • ReadBlock(char[], index, count):填滿緩衝區或結束
  • ReadToEnd():一次性讀完所有內容(大檔慎用)
  • CurrentEncoding:獲取實際使用編碼

二、StreamWriter 寫入文字檔

建構與寫入

// 追加模式開啟
FileStream fs = new FileStream(@"C:\abc.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); // 預設 UTF-8

for (char c = 'a'; c <= 'z'; c++)
    sw.Write(c); // 寫入單字元(無換行)

sw.Close(); fs.Close();

FileMode.Append 將寫入位置定位至檔案末尾,保留原有內容。

常用寫入方法

  • AutoFlush 屬性:每次寫入自動 Flush(效能較差)
  • 方法說明
    Write(value)寫入各類型 ToString 結果
    WriteLine(value)寫入並附加換行符
    Write(char[])寫入字元陣列
    Flush()強制將緩衝區寫入底層流

    驗證寫入結果

    // 重新開啟讀取驗證
    FileStream fs2 = new FileStream(@"c:\abc.txt", FileMode.Open, FileAccess.ReadWrite);
    StreamReader sr2 = new StreamReader(fs2);
    string line = sr2.ReadLine();
    while (line != null) { Console.WriteLine(line); line = sr2.ReadLine(); }
    sr2.Close(); fs2.Close();

    輸出顯示原有內容後接續 abcdefghijklmnopqrstuvwxyz,確認追加成功。

    三、最佳實踐與現代化建議

    1. 使用 using 區塊確保釋放資源:
      using (var sr = new StreamReader(@"c:\abc.txt"))
      using (var sw = new StreamWriter(@"c:\out.txt"))
      {
          string line;
          while ((line = sr.ReadLine()) != null)
              sw.WriteLine(line.ToUpper());
      }
    2. 明確指定 Encoding:new StreamReader(path, Encoding.GetEncoding("big5")) 避免亂碼
    3. 大檔案逐行處理:避免 ReadToEnd() 造成記憶體壓力
    4. .NET Core 2.1+ 推薦:File.ReadLines()、File.WriteAllLinesAsync() 等高階 API,內建非同步與資源管理

    四、編碼與 BOM 關鍵知識

    • 預設 Encoding.UTF8 含 BOM(EF BB BF)
    • new UTF8Encoding(false) 建立無 BOM 實例
    • 跨平台/跨系統交換建議使用 UTF-8 無 BOM
    • 中文舊系統常用 Big5/GB2312,讀寫時必須對應指定

    StreamReader/StreamWriter 是文字檔處理的基石,掌握其建構選項、緩衝機制與編碼處理,能避免 90% 的檔案亂碼與資源洩漏問題。

    StreamReader 讀取對比 檔案原始內容 StreamWriter 寫入後讀取 檔案寫入後內容
    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved