錯誤描述
環境
- dotnet core 2.1 2.2 dotnet core 3.1 dotnet core 5.0
現象
當代碼中使用
System.Text.Encoding.GetEncoding("GB2312") //或者 System.Text.Encoding.GetEncoding("GBK")
會拋出異常:
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.
或者
Unhandled Exception: System.ArgumentException: 'GBK' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
解決
原因
使用如下代碼檢查支持的編碼:
System.Text.Encoding.GetEncodings();
發現獲得的編碼中沒有GB2312或者GBK。
解決辦法
第一步
向項目中添加如下包:
System.Text.Encoding.CodePages
根據 System.Text.Encoding.CodePages nuget主頁 的描述,這個包能為程序提供 Windows-1252, Shift-JIS, and GB2312 三種編碼。
Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.
所以導入這個包之后,我們將能使用 GB2312 編碼。
在 .csproj
文件中應添加如下代碼:
<ItemGroup> <PackageReference Include="System.Text.Encoding.CodePages" Version="4.4.0" /> </ItemGroup>
或者在項目目錄執行如下命令:
dotnet add package System.Text.Encoding.CodePages --version 4.4.0
當然,其中的版本號需要自行修改為最新。此時(2018.02.22)最新版是4.4.0 。
別忘了執行 dotnet restore
。
第二步
根據錯誤提示,我們需要對引用的編碼使用 Encoding.RegisterProvider
函數進行注冊。
在使用 System.Text.Encoding.GetEncoding ("GB2312")
之前,在代碼中執行:
System.Text.Encoding.RegisterProvider (System.Text.CodePagesEncodingProvider.Instance);
注冊完之后,獲取 GB2312 編碼對象就不會報錯了,並且可以正常使用其中的函數。
其他問題
至此我們解決了關於 GB2312 編碼的問題。但是程序中仍然無法使用 GBK 編碼。針對 GBK 編碼數據的解析問題仍存在。