准备文件 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);
}
}
}
}