天天看點

【.Net Core】.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.”,解決方法如下

報錯資訊 

為了解決中文亂碼問題,使用了如下代碼

byte[] response1 = await client.GetByteArrayAsync(url1);
string temp = Encoding.GetEncoding("GB2312").GetString(response1);
           

 報錯如下

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

【.Net Core】.NET Core中使用編碼GB2312報錯‘GB2312‘ is not a supported encoding name解決方案

2、在使用編碼方法(Encoding.GetEncoding("GB2312"))之前,對編碼進行注冊( Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);),代碼如下 

var url1 = "需要抓取新聞清單的url";
//以byte[]擷取html
byte[] response1 = await client.GetByteArrayAsync(url1);
//将byte[]重新編碼成GB2312;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string temp = Encoding.GetEncoding("GB2312").GetString(response1);
           

修改完成後重新編譯成功

繼續閱讀