.NET Core GB2312 coding error in the use of

Transfer from  https://www.cnblogs.com/chr-wonder/p/8464204.html

——————————————————————————————

wrong description

surroundings

  • dotnet 2.1.4

phenomenon

When used in the code

System.Text.Encoding.GetEncoding("GB2312")
//或者
System.Text.Encoding.GetEncoding("GBK")

It 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

Check support using the following code encoding:

System.Text.Encoding.GetEncodings();

It found not obtained encoding GB2312 or GBK.

Solution

first step

Add the following packages to the project:

System.Text.Encoding.CodePages

According  System.Text.Encoding.CodePages nuget home page  described, this package provides Windows-1252, Shift-JIS, and GB2312 three coding for the program.

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  .csproj document 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 need to amend its own version to date. At this time (2018.02.22) The latest version is 4.4.0.

Do not forget to perform  dotnet restore .

The second step

According to error, we need to use coded references  Encoding.RegisterProvider to 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, GB2312 encoding object will not get the error, and can function normally use them.

other problems

So far we have solved the question of GB2312 coding. However, the program still can not be used GBK coding. Resolve the problem for GBK encoded data still exists.

Published 131 original articles · won praise 22 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104719804