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

C# 讀取中文文字檔:編碼指定與緩衝區正確釋放

     編輯:ASP.NET 基礎

問題背景

使用 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 編碼。
  • using 區塊:自動呼叫 Dispose(),內含 Flush() 並關閉資源流。
  • 手動 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,仍需手動指定
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved