.NET Core 中使用GB2312编码报错的问题

错误描述

环境

  • dotnet 2.1.4

现象

当代码中使用ide

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.编码

或者rest

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.code

解决

缘由

使用以下代码检查支持的编码:orm

System.Text.Encoding.GetEncodings();

发现得到的编码中没有GB2312或者GBK。对象

解决办法

第一步get

向项目中添加以下包:io

System.Text.Encoding.CodePagesform

根据 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 编码数据的解析问题仍存在。

相关文章
相关标签/搜索