WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

Posted on   WebEnh  阅读(2620)  评论(0编辑  收藏  举报

错误描述

环境

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

文章转载请注明出处,并附带本文连接。如若有心,请在评论中说明将此文转载至何处。谢谢合作。

 

 
 
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2017-07-05 10个财务工作中常用的 Excel 万能公式
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多