准備文件 hello.txt
直接使用 Windows 記事本保存的中文內容,默認編碼顯示為 ANSI,實際編碼是 GB2312。
ANSI全稱(American National Standard Institite)美國國家標准學會(美國的一個非營利組織),首先ANSI不是指的一種特定的編碼,而是不同地區擴展編碼方式的統稱,各個國家和地區所獨立制定的兼容ASCII,但互相不兼容的字符編碼,微軟統稱為ANSI編碼

C# 讀取文件
一般情況下,C# 讀取文件方式為
string filename = "hello.txt";
StreamReader sr = new StreamReader(File.OpenRead(filename));
但是直接運行會報錯,原因是 StreamReader 默認使用 UTF8 讀取文件,無法正確識別 GB2312 編碼文件
很多文章建議修改方式為讀取時設置編碼 Encoding.Default,比如
StreamReader sr = new StreamReader(File.OpenRead(filename), Encoding.Default);
這樣讀取時的確沒有報錯,但是讀取到的內容是亂碼,無法使用,還是需要指定 GB2312 編碼讀取才行
但是 .net core 並不能直接指定 GB2312 編碼,需要通過注冊的方式
修改后,完整的讀取文件的代碼為
using System;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string filename = "hello.txt";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
StreamReader sr = new StreamReader(File.OpenRead(filename), Encoding.GetEncoding("GB2312"));
string s;
while((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
