C#無(wú)BOM文件頭,按文件內(nèi)容識(shí)別編碼
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
一)需求
二)探討 //判斷上傳的文件的編碼是否是UTF8,buff為上傳文件的字節(jié)流
三)最終的方案
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; } } Encoding encode; StreamReader srtest = new StreamReader(file.FullName,Encoding.Default); int p = utf8_probability(Encoding.Default.GetBytes(srtest.ReadToEnd())); if( p>80 ) encode = Encoding.GetEncoding(65001);//utf8 else encode = Encoding.Default; srtest.Close(); 該文章在 2023/8/23 11:10:02 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |