一段检测文本文件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;
}
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;
}
相关文章推荐
- 读入文件并将其转换成String的小一段代码
- 一段Parsec CSV文件的haskell代码
- 一段读取文件时显示进度条的代码(CSDN上收录)
- java 检测文本、文件编码(未测试)
- python代码统计大文本文件行数
- 一段显示下载进度条的下载文件代码
- 自己动手实现简易代码生成器、采用文本模板文件生成服务层、服务层接口代码的做法参考
- 一段老师写的,C#文件读取代码例子
- .Net快速获取网络文本文件最后一段文字-小应用
- 写入本地路径时,文件是只读的,在前面加上一段代码可以解决这个问题
- PHP批量检测并去除文件BOM头代码实例
- PHP批量检测并去除文件BOM头代码实例
- JavaScript 浏览器检测提示框【每日一段代码68】
- PHP检测每一段代码执行时间
- FindNextFile 蚊子132 给大家写一段通用的文件查找代码,非常简单明了
- txt文本文件编码格式-图片文件类型检测-音视频文件信息
- 请写一段 PHP 代码 ,确保多个进程同时写入同一个文件成功
- 一段简单的内存检测代码
- 一段简单加载配置文件的代码
- Android读写Txt文本文件代码