前提
- 业务需求需要在linux 上读取gb2312编码的文件.
- dotnetcore 默认不支持gb2312
- linux 也不支持gb2312
结果
- 通过添加 System.Text.Encoding.CodePages Nuget 包可以实现gb2312 支持
需要添加在程序启动时添加下列代码
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
- 使用下面的方法读取文件记得把 detectEncodingFromByteOrderMarks 设为false. 不然你会像我一样浪费几个小时.
//
// 摘要:
// Initializes a new instance of the System.IO.StreamReader class for the specified
// file name, with the specified character encoding and byte order mark detection
// option.
//
// 参数:
// path:
// The complete file path to be read.
//
// encoding:
// The character encoding to use.
//
// detectEncodingFromByteOrderMarks:
// Indicates whether to look for byte order marks at the beginning of the file.
//
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks);
// Exmaple
using var reader = new StreamReader(filename,System.Text.Encoding.GetEncoding("gb2312"), false);
总结
- 当程序将文件保存在磁盘上之后,使用 file 命令查看文件格式会发现,格式变成了 utf8.
- 所以当 detectEncodingFromByteOrderMarks=true 时, 这个方法就会忽略参数指定的gb2312,仍然使用检测到的utf8 编码读取文件.
网友评论