Auto encoding detect in C# [duplicate]

2020-02-12 08:34发布

Possible Duplicate:
Determine a string's encoding in C#

Many text editorsr (like Notepad++) can detect encoding of arbitrary file. Can I detect encodoing of file in C#?

标签: c# .net encoding
1条回答
2楼-- · 2020-02-12 08:51

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);
        }
    }
}
查看更多
登录 后发表回答