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

C# StreamReader/StreamWriter 文字串流讀寫完整指南:編碼、緩衝、逐行處理與最佳實務

     編輯:關於C語言

一、為什麼需要 StreamReader/Writer?

FileStream 僅處理位元組,文字處理需自行處理編碼轉換、換行符、緩衝。StreamReader/Writer 封裝字元級讀寫,支援多種編碼、自動緩衝、逐行讀取,是文字檔 I/O 的標準選擇。

二、StreamReader 核心建構函數

建構函數用途
new StreamReader(Stream)包裝現有串流(如 FileStream)
new StreamReader(string path)直接開啟檔案(預設 UTF-8)
new StreamReader(string path, Encoding)指定編碼
new StreamReader(Stream, Encoding)串流+編碼
new StreamReader(..., bool detectEncodingFromByteOrderMarks)自動偵測 BOM

逐行讀取標準模式


// 方式 1:直接路徑
using (StreamReader sr = new StreamReader(@"C:\abc.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
        Console.WriteLine(line);
}

// 方式 2:包裝 FileStream(可控制 FileMode/Access/Share)
using (FileStream fs = new FileStream(@"C:\abc.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
    string line;
    while ((line = sr.ReadLine()) != null)
        Console.WriteLine(line);
}

StreamReader讀取結果 原始檔案內容對比

其他實用方法

  • ReadToEnd():一次讀完所有文字(小檔案適用)
  • ReadBlock(char[], index, count):填充字元陣列
  • Peek():預覽下一字元不消耗
  • CurrentEncoding:取得實際使用編碼

三、StreamWriter 核心建構函數

建構函數用途
new StreamWriter(Stream)包裝串流
new StreamWriter(string path)建立/覆寫檔案(預設 UTF-8 無 BOM)
new StreamWriter(string path, bool append)append=true 附加模式
new StreamWriter(..., Encoding)指定編碼

寫入標準模式


// 附加模式寫入 a-z
using (FileStream fs = new FileStream(@"C:\abc.txt", FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
    for (char c = 'a'; c <= 'z'; c++)
        sw.Write(c); // 無換行
    sw.WriteLine(); // 寫入換行
}

// 覆寫模式寫入多行
using (StreamWriter sw = new StreamWriter(@"C:\log.txt"))
{
    sw.WriteLine("第一行");
    sw.WriteLine("第二行 {0}", DateTime.Now);
    sw.Write("無換行 ");
    sw.Write("續寫");
}

StreamWriter寫入結果 寫入後檔案內容

關鍵屬性與方法

  • AutoFlush:每次寫入自動 Flush()(效能較差,除非即時日誌)
  • NewLine:自訂換行字串(預設 Environment.NewLine)
  • Write/WriteLine 多載支援格式化字串

四、編碼處理關鍵知識

鐵律:明確指定編碼,永遠不要依賴 Encoding.Default。

五、using 區塊與資源釋放鐵律


// 編譯器展開為 try/finally 確保 Dispose()
using (StreamReader sr = new StreamReader(path))
{
    // ...
} // 此處自動 sr.Dispose() → 關閉底層串流
  • 巢狀 using 依序釋放(外層先建立,內層先釋放)
  • 若手動管理,必須在 finally 呼叫 Close()/Dispose()

六、效能優化建議

  1. 大檔案逐行處理(ReadLine),避免 ReadToEnd 佔用大量記憶體
  2. 批次寫入時關閉 AutoFlush,最後統一 Flush()
  3. 超大檔案考慮 File.ReadLines(延遲列舉)或 MemoryMappedFile
  4. 頻繁開關同一檔案改用 FileStream 保持開啟

總結

StreamReader/Writer 是 .NET 文字檔 I/O 的標準高層 API,封裝編碼轉換、緩衝管理、換行規範化。掌握建構函數選擇、編碼明確指定、using 區塊資源管理、逐行處理大檔案四大核心,即能編寫健壯、高效、跨平台的文字檔案處理程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
編碼適用場景BOM
Encoding.UTF8跨平台、Web、現代應用首選可選(預設無)
Encoding.UnicodeUTF-16 LE,Windows 內部有
Encoding.BigEndianUnicodeUTF-16 BE有
Encoding.GetEncoding(950)Big5 繁體中文(舊系統相容)無
Encoding.Default系統當前 ANSI 頁碼(不可攜帶)無