.NET CORE中Encoding对GB2312等编码的支持

mac2022-06-30  85

  最近.NET CORE做网络爬虫的时候,遇到了charset=gbk,转码的时候,发现直接使用Encoding.GetEncoding(“GB2312”)抛异常了。好吧,看到这个的时候,我是一脸懵逼的。无奈,毕竟.NET CORE不是.Net,做过精简,做过调整。然后,开始搜索相关资料,参考网址http://www.cnblogs.com/artech/p/encoding-registeration-4-net-core.html,做了两步操作:

1. 引入了System.Text.Encoding.CodePages.dll

2. 在启动的时候,注册EncodingProvider,执行代码如下:

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

这样,就可以在程序中使用GB3212编码了。

另外,我也在msdn上找到了相关资料,参考地址如下:

1. https://msdn.microsoft.com/en-us/library/ms404377(v=vs.110).aspx

相关内容:

Platform Notes: .NET Core

By default, .NET Core does not make available any code page encodings other than code page 28591 and the Unicode encodings, such as UTF-8 and UTF-16. However, you can add the code page encodings found in standard Windows apps that target the .NET Framework to your app. For complete information, see the CodePagesEncodingProvider topic.

注解:默认情况下,.NET CORE只支持28951、UTF-8、UTF-16,其他的编码格式均不支持。但是,我们可以在.NET Framework开发的标准Windows应用程序中使用。完整的信息,请查看CodePagesEncodingProvider。CodePagesEncodingProvider的url就是如下2中的地址。

2. https://msdn.microsoft.com/en-us/library/mt643901(v=vs.110).aspx

相关内容:

The CodePagesEncodingProvider class extends EncodingProvider to make these code pages available to .NET Native and Universal Windows Platform (UWP) apps. To use these additional code pages, you do the following:

Add a reference to the System.Text.Encoding.CodePages.dll assembly to your project.Retrieve a CodePagesEncodingProvider object from the static CodePagesEncodingProvider.Instance property.Pass the CodePagesEncodingProvider object to the Encoding.RegisterProvider method.

After an EncodingProvider object is registered, the encodings that it supports are available by calling the overloads of Encoding.GetEncoding; you should not call the EncodingProvider.GetEncoding overloads.

注解:CodePagesEncodingProvider类继承自EncodingProvider,可以使默认情况下不支持的编码,在.NET Native和UWP应用程序中进行使用。为了能使用这些编码,需要执行如下步骤:

1.添加the System.Text.Encoding.CodePages.dll到项目引用。(可以直接在nuget中下载安装)

2.把静态的CodePagesEncodingProvider.Instance 传递给Encoding.RegisterProvider方法,即执行代码:Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

 

 

备注:The CodePagesEncodingProvider class is supported in the .NET Native implementation of .NET Core only.

英文翻译的不到位,不过大致意思就是这样,给懒人一个偷懒的机会,高手们就自己体会原文的意境吧!

推荐一下自己的网站:www.mylofter.com:81,平行世界

转载于:https://www.cnblogs.com/mermaidLoft/p/6047423.html

最新回复(0)