使用 StreamReader 讀取中文文字檔,預設編碼為 ASCII 導致亂碼;嘗試 UTF-8 仍亂碼,改用 GB2312 正常。但讀取 1500 行檔案時,輸出檔案總是少幾十行,原因在於緩衝區未正確釋放。
private static void ProcessFile()
{
// 明確指定 GB2312 編碼
using (var reader = new StreamReader(@"d:\1500.txt", Encoding.GetEncoding("GB2312")))
using (var writerEn = new StreamWriter(@"d:\English.txt", false, Encoding.UTF8, 1024))
using (var writerCh = new StreamWriter(@"d:\Chinese.txt", false, Encoding.UTF8, 1024))
{
try
{
int i = 1;
string line;
while ((line = reader.ReadLine()) != null)
{
if (i % 2 == 1) writerEn.WriteLine(line);
else writerCh.WriteLine(line);
i++;
}
Console.WriteLine(i + "\tOK");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
// 關鍵:確保緩衝區寫入磁碟
writerEn.Flush();
writerCh.Flush();
}
}
}
Big5,簡體常用 GB2312/GBK,現代專案優先 UTF-8。可用 Encoding.Default 取得系統預設 ANSI 編碼。Dispose(),內含 Flush() 並關閉資源流。using,必須在 finally 區塊呼叫 Flush(),否則緩衝區資料停留在記憶體,檔案不完整。StreamWriter 第四參數 bufferSize(如 1024)可減少系統呼叫次數。
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(fs, true)) // detectEncodingFromByteOrderMarks = true
{
// 自動偵測 UTF-8/UTF-16 BOM,無 BOM 仍回退 UTF-8
// 若檔案為 GB2312/Big5 且無 BOM,仍需手動指定
}