根据孟子的做法,试了一下:
static Encoding GetEncoding(string filepath)
{
Encoding result = null;
FileStream file = null;
try 
{
file = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);if (file.CanSeek)
{
// get the bom, if there is one
byte[] bom = new byte[4]; 
file.Read(bom, 0, 4);// utf-8
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)
result = System.Text.Encoding.UTF8;
// ucs-2le, ucs-4le, ucs-16le, utf-16, ucs-2, ucs-4
else if ((bom[0] == 0xff && bom[1] == 0xfe) || 
(bom[0] == 0xfe && bom[1] == 0xff) || 
(bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff))
result = System.Text.Encoding.Unicode;
// else ascii
else
result = System.Text.Encoding.ASCII;
}
else
{
// can't detect, set to default
result = System.Text.Encoding.ASCII;
}return result;
}
finally
{
if (null != file) file.Close();
}
}}
但是发现读不到文件中的前两个字节,这两个字节是BOM信息,我用它来判断是否为UTF8文件,该文件是用UltraEdit保存的UTF8 DOS型的文件