一)需求 很多情况下我们需要知道字节流的编码,比如 1) 使用编辑器打开文本文件的时候,编辑器需要识别文本文件的各种编码 2) 上传文件后,分析上传文件字节流需要知道它的编码
二)探讨 不过C#目前还没有现成的函数能够获取,经过和同事的探讨,发现UTF8文件都有一个3字节的头,为“EF BB BF”(称为BOM--Byte Order Mark),判断这个头信息不就可以解决了吗?代码如下:
//判断上传的文件的编码是否是UTF8,buff为上传文件的字节流 enc = Encoding.UTF8; testencbuff = enc.GetPreamble(); if(fileLength>testencbuff.Length && testencbuff[0] == buff[0] && testencbuff[1]==buff[1] && testencbuff[2]==buff[2]) { // 是 UTF8编码 string buffString = enc.GetString(buff); } 不过后来发现,不是所有的UTF8编码的文件都有BOM信息,那如何解决呢?
三)最终的方案 没有BOM信息只有通过逐个字节比较的方式才能解决。幸好已经有人解决这个问题了。推荐大家看: http://dev.csdn.net/Develop/article/10/10961.shtm http://dev.csdn.net/Develop/article/10/10962.shtm 这里判断所有的编码,基本上都是通过字节比较的方式。java代码很容易移植到.NET上,下面是UTF8判断部分的C#代码:
int utf8_probability(byte[] rawtext) { int score = 0; int i, rawtextlen = 0; int goodbytes = 0, asciibytes = 0;
// Maybe also use UTF8 Byte Order Mark: EF BB BF
// Check to see if characters fit into acceptable ranges rawtextlen = rawtext.Length; for (i = 0; i < rawtextlen; i++) { if ((rawtext[i] & (byte)0x7F) == rawtext[i]) { // One byte asciibytes++; // Ignore ASCII, can throw off count } else { int m_rawInt0 = Convert.ToInt16(rawtext[i]); int m_rawInt1 = Convert.ToInt16(rawtext[i+1]); int m_rawInt2 = Convert.ToInt16(rawtext[i+2]);
if (256-64 <= m_rawInt0 && m_rawInt0 <= 256-33 && // Two bytes i+1 < rawtextlen && 256-128 <= m_rawInt1 && m_rawInt1 <= 256-65) { goodbytes += 2; i++; } else if (256-32 <= m_rawInt0 && m_rawInt0 <= 256-17 && // Three bytes i+2 < rawtextlen && 256-128 <= m_rawInt1 && m_rawInt1 <= 256-65 && 256-128 <= m_rawInt2 && m_rawInt2 <= 256-65) { goodbytes += 3; i+=2; } } }
if (asciibytes == rawtextlen) { return 0; }
score = (int)(100 * ((float)goodbytes/(float)(rawtextlen-asciibytes)));
// If not above 98, reduce to zero to prevent coincidental matches // Allows for some (few) bad formed sequences if (score > 98) { return score; } else if (score > 95 && goodbytes > 30) { return score; } else { return 0; }
}
参考资料: 字符检测程序(上) 检测GB2312、BIG5... http://dev.csdn.net/Develop/article/10/article/10/10961.shtm Hello Unicode ——JAVA的中文处理学习笔记 http://www.chedong.com/tech/hello_unicode.html

|