1. 程式人生 > 其它 >.net core中使用GB2312編碼的問題

.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

轉載:https://www.cnblogs.com/liemei/p/7884172.html

本文來自部落格園,作者:.net&new,轉載請註明原文連結:https://www.cnblogs.com/wugh8726254/p/15302391.html