C#中的自动编码检测

可能重复:
在C#中确定字符串的编码

许多文本编辑器(如Notepad ++)可以检测任意文件的编码。 我可以在C#中检测到文件的编码吗?

如果在尝试读取时有BOM, StreamReader将尝试自动检测文件的编码:

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); } } }