且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动编码检测C#

更新时间:2023-02-26 14:23:13

一个的StreamReader 将尝试自动检测一个文件的编码是否有试图读取时一个BOM:

A StreamReader will try to automatically detect the encoding of a file if there's a BOM when trying to read:

public class Program
{
    static void Main(string[] args)
    {
        using (var reader = new StreamReader("foo.txt"))
        {
            // Make sure you read from the file or it won't be able
            // to guess the encoding
            var file = reader.ReadToEnd();
            Console.WriteLine(reader.CurrentEncoding);
        }
    }
}