• .NET Core3.1 中使用GB2312编码报错的问题


    现象

    当代码中使用

    System.Text.Encoding.GetEncoding("GB2312")
    

    会抛出异常:

    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.

    解决

    原因

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

    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.7.1" />
      </ItemGroup>
    

    或者在项目目录执行如下命令:

    dotnet add package System.Text.Encoding.CodePages 

    当然,其中的版本号需要自行修改为最新。此时(2020.05.21)最新版是4.7.1 。

    别忘了执行 dotnet restore

    第二步

    根据错误提示,我们需要对引用的编码使用 Encoding.RegisterProvider 函数进行注册。

    在使用 System.Text.Encoding.GetEncoding ("GB2312") 之前,在代码中执行:

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

    注册完之后,获取 GB2312 编码对象就不会报错了,并且可以正常使用其中的函数。

  • 相关阅读:
    shell中括号的特殊用法 linux if多条件判断
    uboot kernel 博客
    meson 中调用shell script
    200. 岛屿数量
    9. 回文数
    53. 最大子序和
    394. 字符串解码
    32. 最长有效括号
    leetcode排序的题 912. 排序数组 215. 数组中的第K个最大元素
    c++引用和运算符重载思考
  • 原文地址:https://www.cnblogs.com/jingjing-blogs/p/12929149.html
Copyright © 2020-2023  润新知