您的位置:首页 > 编程语言

一段检测文本文件encoding的代码

2008-09-17 19:25 344 查看
Code
Encoding CheckFileEncoding(string fileName)
{
System.Text.Encoding enc = null;
System.IO.FileStream file = new System.IO.FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(file);
byte[] bom = new byte[4]; // Get the byte-order mark, if there is one
br.Read(bom, 0, 4);
if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) || // utf-8
(bom[0] == 0xff && bom[1] == 0xfe) || // ucs-2le, ucs-4le, and ucs-16le
(bom[0] == 0xfe && bom[1] == 0xff) || // utf-16 and ucs-2
(bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) || // ucs-4
(bom[1] == 0 && bom[3] == 0)) // only unicode
{
enc = System.Text.Encoding.Unicode;
}
else
{
enc = System.Text.Encoding.ASCII;
}

file.Close();
return enc;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: