最近.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
相關內容:
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,平行世界