The problem of using GB2312 encoding in .NET Core to report errors

wrong description

surroundings

  • dotnet 2.1.4

phenomenon

When used in code

System.Text.Encoding.GetEncoding("GB2312")
//or
System.Text.Encoding.GetEncoding("GBK")

Will throw an exception:

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.

or

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.

solve

the reason

Use the following code to check the supported encoding:

System.Text.Encoding.GetEncodings();

It is found that there is no GB2312 or GBK in the obtained code.

Solution

first step

Add the following packages to the project:

System.Text.Encoding.CodePages

According to the description of System.Text.Encoding.CodePages nuget homepage , this package can provide programs with Windows-1252, Shift-JIS, and GB2312 encodings.

Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.

So after importing this package, we will be able to use GB2312 encoding.

In the .csprojdocument should add the following code:

  <ItemGroup>
    <PackageReference Include="System.Text.Encoding.CodePages" Version="4.4.0" />
  </ItemGroup>

Or execute the following command in the project directory:

dotnet add package System.Text.Encoding.CodePages --version 4.4.0

Of course, the version number needs to be modified to the latest. At this time (2018.02.22) the latest version is 4.4.0.

Don’t forget to execute dotnet restore.

Second step

According to error, we need to use coded references Encoding.RegisterProviderto register functions.

In use System.Text.Encoding.GetEncoding ("GB2312")prior to execution in the code:

System.Text.Encoding.RegisterProvider (System.Text.CodePagesEncodingProvider.Instance);

After registering, you won’t get an error when you get the GB2312 code object, and you can use the functions normally.


Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *