.net core中使用GB2312編碼的問題


 

最近在用.net core寫一個爬蟲抓取網頁上的數據,碰到了網頁編碼是GBK的頁面,抓取的數據都是亂碼,當使用Encoding.GetEncoding(“GBK”)的時候拋出了異常:

'GBK' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name

當改用GB2312的時候也拋出了同樣的異常:

'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name

從異常上來看是不支持GB2312和GBK。而且提到了需要注冊EncodingProvider的方法。CodePagesEncodingProvider定義在NuGet包“System.Text.Encoding.CodePages”之中。所以我們就需要添加System.Text.Encoding.CodePages的依賴。然后在Project.json中添加

{
"dependencies": { "System.Text.Encoding.CodePages": "4.0.1-rc2-24027" }
}

在代碼中還需要添加Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);如圖:

再次啟動就可以可以使用GB2312


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM