美文网首页
asp.net core Linux 下面使用gb2312 编码

asp.net core Linux 下面使用gb2312 编码

作者: Codmowa | 来源:发表于2020-02-19 17:26 被阅读0次

    前提

      1. 业务需求需要在linux 上读取gb2312编码的文件.
      1. dotnetcore 默认不支持gb2312
      1. linux 也不支持gb2312

    结果

      1. 通过添加 System.Text.Encoding.CodePages Nuget 包可以实现gb2312 支持
        需要添加在程序启动时添加下列代码
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    
    1. 使用下面的方法读取文件记得把 detectEncodingFromByteOrderMarks 设为false. 不然你会像我一样浪费几个小时.
            //
            // 摘要:
            //     Initializes a new instance of the System.IO.StreamReader class for the specified
            //     file name, with the specified character encoding and byte order mark detection
            //     option.
            //
            // 参数:
            //   path:
            //     The complete file path to be read.
            //
            //   encoding:
            //     The character encoding to use.
            //
            //   detectEncodingFromByteOrderMarks:
            //     Indicates whether to look for byte order marks at the beginning of the file.
            //
    
            public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks);
            // Exmaple
            using var reader = new StreamReader(filename,System.Text.Encoding.GetEncoding("gb2312"), false);
    

    总结

      1. 当程序将文件保存在磁盘上之后,使用 file 命令查看文件格式会发现,格式变成了 utf8.
      1. 所以当 detectEncodingFromByteOrderMarks=true 时, 这个方法就会忽略参数指定的gb2312,仍然使用检测到的utf8 编码读取文件.

    相关文章

      网友评论

          本文标题:asp.net core Linux 下面使用gb2312 编码

          本文链接:https://www.haomeiwen.com/subject/lpgafhtx.html