.NET Core中使用编码GB2312报错‘GB2312‘ is not a supported encoding name 解决方案
问题描述
今天在.Net Core中对外网新闻进行爬虫抓取,最初抓取到的新闻中出现了乱码,后来通过GB2312进行了编码,结果报错“ Unhandled Exception: System.ArgumentException: 'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.”
Unhandled Exception: System.ArgumentException: 'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
————————————————
解决方案
1. 项目添加引用
在NuGet包中安装包System.Text.Encoding.CodePages
System.Text.Encoding.CodePages
2. 对编码进行注册
在使用编码方法(Encoding.GetEncoding("GB2312"))之前,对编码进行注册( Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);),代码如下
在 startUp.cs 类 ConfigureServices 方法中对编码进行注册
#region 配置GB2312编码
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endregion
3. 使用
var encodGB2312 = Encoding.GetEncoding("GB2312");
byte[] byte03 = encodGB2312.GetBytes("04033屏幕测试");
参考: https://blog.csdn.net/liuzhenhe1988/article/details/109091568