如何让.NET Core支持GB2312和GBK

在.NET Core中,默认是不支持GB2312和GBK编码的。

例如我们如果新建一个.NET Core控制台项目,然后在其Main方法中使用如下代码:

using System;
using System.Text;

namespace NetCoreCoding
{
    class Program
    {
        static void Main(string[] args)
        {
            string textToEncode = "今天是个好天气";

            byte[] byteData = Encoding.GetEncoding("gb2312").GetBytes(textToEncode);

            Console.WriteLine("Press key to end...");
            Console.ReadKey();
        }
    }
}

运行到Encoding.GetEncoding("gb2312")时,会出现异常:

异常信息如下:

'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

所以在.NET Core中如果我们要使用GB2312和GBK编码,需要给项目引入一个Nuget包:

System.Text.Encoding.CodePages

然后使用Encoding.RegisterProvider方法进行注册Provider,我们将.NET Core控制台项目的Main方法改为如下:

using System;
using System.Text;

namespace NetCoreCoding
{
    class Program
    {
        static void Main(string[] args)
        {
            string textToEncode = "今天是个好天气";

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//注册Nuget包System.Text.Encoding.CodePages中的编码到.NET Core
            byte[] byteData = Encoding.GetEncoding("gb2312").GetBytes(textToEncode);

            Console.WriteLine("Press key to end...");
            Console.ReadKey();
        }
    }
}

现在再调用Encoding.GetEncoding("gb2312")就不会抛出异常了。

猜你喜欢

转载自www.cnblogs.com/OpenCoder/p/10386540.html
今日推荐