.Net Core C# 读取 Windows 文件


准备文件 hello.txt

直接使用 Windows 记事本保存的中文内容,默认编码显示为 ANSI,实际编码是 GB2312。

ANSI全称(American National Standard Institite)美国国家标准学会(美国的一个非营利组织),首先ANSI不是指的一种特定的编码,而是不同地区扩展编码方式的统称,各个国家和地区所独立制定的兼容ASCII,但互相不兼容的字符编码,微软统称为ANSI编码

C# 读取文件

一般情况下,C# 读取文件方式为

string filename = "hello.txt";
StreamReader sr = new StreamReader(File.OpenRead(filename));

但是直接运行会报错,原因是 StreamReader 默认使用 UTF8 读取文件,无法正确识别 GB2312 编码文件

很多文章建议修改方式为读取时设置编码 Encoding.Default,比如

StreamReader sr = new StreamReader(File.OpenRead(filename), Encoding.Default);

这样读取时的确没有报错,但是读取到的内容是乱码,无法使用,还是需要指定 GB2312 编码读取才行

但是 .net core 并不能直接指定 GB2312 编码,需要通过注册的方式

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

修改后,完整的读取文件的代码为

using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "hello.txt";
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            StreamReader sr = new StreamReader(File.OpenRead(filename), Encoding.GetEncoding("GB2312"));
            string s;
            while((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM