许多文本编辑器(如Notepad ++)可以检测任意文件的编码。我可以在C#中检测到文件的编码吗?
答案 0 :(得分:8)
如果在尝试阅读时出现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);
}
}
}