c#如何检测文本文件的编码

前端之家收集整理的这篇文章主要介绍了c#如何检测文本文件的编码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.IO;
  5.  
  6. namespace KlerksSoft
  7. {
  8. public static class TextFileEncodingDetector
  9. {
  10. /*
  11. * Simple class to handle text file encoding woes (in a primarily English-speaking tech
  12. * world).
  13. *
  14. * - This code is fully managed,no shady calls to MLang (the unmanaged codepage
  15. * detection library originally developed for Internet Explorer).
  16. *
  17. * - This class does NOT try to detect arbitrary codepages/charsets,it really only
  18. * aims to differentiate between some of the most common variants of Unicode
  19. * encoding,and a "default" (western / ascii-based) encoding alternative provided
  20. * by the caller.
  21. *
  22. * - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and
  23. * Windows-1252 (in .Net,also incorrectly called "ASCII") encodings,we use a
  24. * heuristic - so the more of the file we can sample the better the guess. If you
  25. * are going to read the whole file into memory at some point,then best to pass
  26. * in the whole byte byte array directly. Otherwise,decide how to trade off
  27. * reliability against performance / memory usage.
  28. *
  29. * - The UTF-8 detection heuristic only works for western text,as it relies on
  30. * the presence of UTF-8 encoded accented and other characters found in the upper
  31. * ranges of the Latin-1 and (particularly) Windows-1252 codepages.
  32. *
  33. * - For more general detection routines,see existing projects / resources:
  34. * - MLang - Microsoft library originally for IE6,available in Windows XP and later APIs now (I think?)
  35. * - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
  36. * - CharDet - Mozilla browser's detection routines
  37. * - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
  38. * - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
  39. *
  40. * Copyright Tao Klerks,Jan 2010,[email protected]
  41. * Licensed under the modified BSD license:
  42. *
  43.  
  44. Redistribution and use in source and binary forms,with or without modification,are
  45. permitted provided that the following conditions are met:
  46.  
  47. - Redistributions of source code must retain the above copyright notice,this list of
  48. conditions and the following disclaimer.
  49. - Redistributions in binary form must reproduce the above copyright notice,this list
  50. of conditions and the following disclaimer in the documentation and/or other materials
  51. provided with the distribution.
  52. - The name of the author may not be used to endorse or promote products derived from
  53. this software without specific prior written permission.
  54.  
  55. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING,BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  56. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  57. DIRECT,INDIRECT,INCIDENTAL,SPECIAL,EXEMPLARY,OR CONSEQUENTIAL DAMAGES (INCLUDING,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA,OR
  58. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,WHETHER IN CONTRACT,STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  59. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,EVEN IF ADVISED OF THE POSSIBILITY
  60. OF SUCH DAMAGE.
  61.  
  62. *
  63. */
  64.  
  65. const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements
  66.  
  67. public static Encoding DetectTextFileEncoding(string InputFilename,Encoding DefaultEncoding)
  68. {
  69. using (FileStream textfileStream = File.OpenRead(InputFilename))
  70. {
  71. return DetectTextFileEncoding(textfileStream,DefaultEncoding,_defaultHeuristicSampleSize);
  72. }
  73. }
  74.  
  75. public static Encoding DetectTextFileEncoding(FileStream InputFileStream,Encoding DefaultEncoding,long HeuristicSampleSize)
  76. {
  77. if (InputFileStream == null)
  78. throw new ArgumentNullException("Must provide a valid Filestream!","InputFileStream");
  79.  
  80. if (!InputFileStream.CanRead)
  81. throw new ArgumentException("Provided file stream is not readable!","InputFileStream");
  82.  
  83. if (!InputFileStream.CanSeek)
  84. throw new ArgumentException("Provided file stream cannot seek!","InputFileStream");
  85.  
  86. Encoding encodingFound = null;
  87.  
  88. long originalPos = InputFileStream.Position;
  89.  
  90. InputFileStream.Position = 0;
  91.  
  92. //First read only what we need for BOM detection
  93.  
  94. byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
  95. InputFileStream.Read(bomBytes,bomBytes.Length);
  96.  
  97. encodingFound = DetectBOMBytes(bomBytes);
  98.  
  99. if (encodingFound != null)
  100. {
  101. InputFileStream.Position = originalPos;
  102. return encodingFound;
  103. }
  104.  
  105. //BOM Detection Failed,going for heuristics now.
  106. // create sample byte array and populate it
  107. byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
  108. Array.Copy(bomBytes,sampleBytes,bomBytes.Length);
  109. if (InputFileStream.Length > bomBytes.Length)
  110. InputFileStream.Read(sampleBytes,bomBytes.Length,sampleBytes.Length - bomBytes.Length);
  111. InputFileStream.Position = originalPos;
  112.  
  113. //test byte array content
  114. encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);
  115.  
  116. if (encodingFound != null)
  117. return encodingFound;
  118. else
  119. return DefaultEncoding;
  120. }
  121.  
  122. public static Encoding DetectTextByteArrayEncoding(byte[] TextData,Encoding DefaultEncoding)
  123. {
  124. if (TextData == null)
  125. throw new ArgumentNullException("Must provide a valid text data byte array!","TextData");
  126.  
  127. Encoding encodingFound = null;
  128.  
  129. encodingFound = DetectBOMBytes(TextData);
  130.  
  131. if (encodingFound != null)
  132. {
  133. return encodingFound;
  134. }
  135. else
  136. {
  137. //test byte array content
  138. encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);
  139.  
  140. if (encodingFound != null)
  141. return encodingFound;
  142. else
  143. return DefaultEncoding;
  144. }
  145.  
  146. }
  147.  
  148. public static Encoding DetectBOMBytes(byte[] BOMBytes)
  149. {
  150. if (BOMBytes == null)
  151. throw new ArgumentNullException("Must provide a valid BOM byte array!","BOMBytes");
  152.  
  153. if (BOMBytes.Length < 2)
  154. return null;
  155.  
  156. if (BOMBytes[0] == 0xff
  157. && BOMBytes[1] == 0xfe
  158. && (BOMBytes.Length < 4
  159. || BOMBytes[2] != 0
  160. || BOMBytes[3] != 0
  161. )
  162. )
  163. return Encoding.Unicode;
  164.  
  165. if (BOMBytes[0] == 0xfe
  166. && BOMBytes[1] == 0xff
  167. )
  168. return Encoding.BigEndianUnicode;
  169.  
  170. if (BOMBytes.Length < 3)
  171. return null;
  172.  
  173. if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
  174. return Encoding.UTF8;
  175.  
  176. if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
  177. return Encoding.UTF7;
  178.  
  179. if (BOMBytes.Length < 4)
  180. return null;
  181.  
  182. if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
  183. return Encoding.UTF32;
  184.  
  185. if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
  186. return Encoding.GetEncoding(12001);
  187.  
  188. return null;
  189. }
  190.  
  191. public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
  192. {
  193. long oddBinaryNullsInSample = 0;
  194. long evenBinaryNullsInSample = 0;
  195. long suspicIoUsUTF8SequenceCount = 0;
  196. long suspicIoUsUTF8BytesTotal = 0;
  197. long likelyUSASCIIBytesInSample = 0;
  198.  
  199. //Cycle through,keeping count of binary null positions,possible UTF-8
  200. // sequences from upper ranges of Windows-1252,and probable US-ASCII
  201. // character counts.
  202.  
  203. long currentPos = 0;
  204. int skipUTF8Bytes = 0;
  205.  
  206. while (currentPos < SampleBytes.Length)
  207. {
  208. //binary null distribution
  209. if (SampleBytes[currentPos] == 0)
  210. {
  211. if (currentPos % 2 == 0)
  212. evenBinaryNullsInSample++;
  213. else
  214. oddBinaryNullsInSample++;
  215. }
  216.  
  217. //likely US-ASCII characters
  218. if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
  219. likelyUSASCIIBytesInSample++;
  220.  
  221. //suspicIoUs sequences (look like UTF-8)
  222. if (skipUTF8Bytes == 0)
  223. {
  224. int lengthFound = DetectSuspicIoUsUTF8SequenceLength(SampleBytes,currentPos);
  225.  
  226. if (lengthFound > 0)
  227. {
  228. suspicIoUsUTF8SequenceCount++;
  229. suspicIoUsUTF8BytesTotal += lengthFound;
  230. skipUTF8Bytes = lengthFound - 1;
  231. }
  232. }
  233. else
  234. {
  235. skipUTF8Bytes--;
  236. }
  237.  
  238. currentPos++;
  239. }
  240.  
  241. //1: UTF-16 LE - in english / european environments,this is usually characterized by a
  242. // high proportion of odd binary nulls (starting at 0),with (as this is text) a low
  243. // proportion of even binary nulls.
  244. // The thresholds here used (less than 20% nulls where you expect non-nulls,and more than
  245. // 60% nulls where you do expect nulls) are completely arbitrary.
  246.  
  247. if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
  248. && ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
  249. )
  250. return Encoding.Unicode;
  251.  
  252. //2: UTF-16 BE - in english / european environments,this is usually characterized by a
  253. // high proportion of even binary nulls (starting at 0),with (as this is text) a low
  254. // proportion of odd binary nulls.
  255. // The thresholds here used (less than 20% nulls where you expect non-nulls,and more than
  256. // 60% nulls where you do expect nulls) are completely arbitrary.
  257.  
  258. if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
  259. && ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
  260. )
  261. return Encoding.BigEndianUnicode;
  262.  
  263. //3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content
  264. // using regexp,in his w3c.org unicode FAQ entry:
  265. // http://www.w3.org/International/questions/qa-forms-utf-8
  266. // adapted here for C#.
  267. string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
  268. Regex UTF8Validator = new Regex(@"\A("
  269. + @"[\x09\x0A\x0D\x20-\x7E]"
  270. + @"|[\xC2-\xDF][\x80-\xBF]"
  271. + @"|\xE0[\xA0-\xBF][\x80-\xBF]"
  272. + @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
  273. + @"|\xED[\x80-\x9F][\x80-\xBF]"
  274. + @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
  275. + @"|[\xF1-\xF3][\x80-\xBF]{3}"
  276. + @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
  277. + @")*\z");
  278. if (UTF8Validator.IsMatch(potentiallyMangledString))
  279. {
  280. //Unfortunately,just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
  281. //If all the characters are in the 0-127 range,no harm done,most western charsets are same as UTF-8 in these ranges.
  282. //If some of the characters were in the upper range (western accented characters),however,they would likely be mangled to 2-byte by the UTF-8 encoding process.
  283. // So,we need to play stats.
  284.  
  285. // The "Random" likelihood of any pair of randomly generated characters being one
  286. // of these "suspicIoUs" character sequences is:
  287. // 128 / (256 * 256) = 0.2%.
  288. //
  289. // In western text data,that is SIGNIFICANTLY reduced - most text data stays in the <127
  290. // character range,so we assume that more than 1 in 500,000 of these character
  291. // sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
  292. //
  293. // We can only assume these character sequences will be rare if we ALSO assume that this
  294. // IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is
  295. // not already suspicIoUs sequences) should be plain US-ASCII bytes. This,I
  296. // arbitrarily decided,should be 80% (a random distribution,eg binary data,would yield
  297. // approx 40%,so the chances of hitting this threshold by accident in random data are
  298. // VERY low).
  299.  
  300. if ((suspicIoUsUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicIoUs sequences
  301. && (
  302. //all suspicIoUs,so cannot evaluate proportion of US-Ascii
  303. SampleBytes.Length - suspicIoUsUTF8BytesTotal == 0
  304. ||
  305. likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspicIoUsUTF8BytesTotal) >= 0.8
  306. )
  307. )
  308. return Encoding.UTF8;
  309. }
  310.  
  311. return null;
  312. }
  313.  
  314. private static bool IsCommonUSASCIIByte(byte testByte)
  315. {
  316. if (testByte == 0x0A //lf
  317. || testByte == 0x0D //cr
  318. || testByte == 0x09 //tab
  319. || (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
  320. || (testByte >= 0x30 && testByte <= 0x39) //digits
  321. || (testByte >= 0x3A && testByte <= 0x40) //common punctuation
  322. || (testByte >= 0x41 && testByte <= 0x5A) //capital letters
  323. || (testByte >= 0x5B && testByte <= 0x60) //common punctuation
  324. || (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
  325. || (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
  326. )
  327. return true;
  328. else
  329. return false;
  330. }
  331.  
  332. private static int DetectSuspicIoUsUTF8SequenceLength(byte[] SampleBytes,long currentPos)
  333. {
  334. int lengthFound = 0;
  335.  
  336. if (SampleBytes.Length >= currentPos + 1
  337. && SampleBytes[currentPos] == 0xC2
  338. )
  339. {
  340. if (SampleBytes[currentPos + 1] == 0x81
  341. || SampleBytes[currentPos + 1] == 0x8D
  342. || SampleBytes[currentPos + 1] == 0x8F
  343. )
  344. lengthFound = 2;
  345. else if (SampleBytes[currentPos + 1] == 0x90
  346. || SampleBytes[currentPos + 1] == 0x9D
  347. )
  348. lengthFound = 2;
  349. else if (SampleBytes[currentPos + 1] >= 0xA0
  350. && SampleBytes[currentPos + 1] <= 0xBF
  351. )
  352. lengthFound = 2;
  353. }
  354. else if (SampleBytes.Length >= currentPos + 1
  355. && SampleBytes[currentPos] == 0xC3
  356. )
  357. {
  358. if (SampleBytes[currentPos + 1] >= 0x80
  359. && SampleBytes[currentPos + 1] <= 0xBF
  360. )
  361. lengthFound = 2;
  362. }
  363. else if (SampleBytes.Length >= currentPos + 1
  364. && SampleBytes[currentPos] == 0xC5
  365. )
  366. {
  367. if (SampleBytes[currentPos + 1] == 0x92
  368. || SampleBytes[currentPos + 1] == 0x93
  369. )
  370. lengthFound = 2;
  371. else if (SampleBytes[currentPos + 1] == 0xA0
  372. || SampleBytes[currentPos + 1] == 0xA1
  373. )
  374. lengthFound = 2;
  375. else if (SampleBytes[currentPos + 1] == 0xB8
  376. || SampleBytes[currentPos + 1] == 0xBD
  377. || SampleBytes[currentPos + 1] == 0xBE
  378. )
  379. lengthFound = 2;
  380. }
  381. else if (SampleBytes.Length >= currentPos + 1
  382. && SampleBytes[currentPos] == 0xC6
  383. )
  384. {
  385. if (SampleBytes[currentPos + 1] == 0x92)
  386. lengthFound = 2;
  387. }
  388. else if (SampleBytes.Length >= currentPos + 1
  389. && SampleBytes[currentPos] == 0xCB
  390. )
  391. {
  392. if (SampleBytes[currentPos + 1] == 0x86
  393. || SampleBytes[currentPos + 1] == 0x9C
  394. )
  395. lengthFound = 2;
  396. }
  397. else if (SampleBytes.Length >= currentPos + 2
  398. && SampleBytes[currentPos] == 0xE2
  399. )
  400. {
  401. if (SampleBytes[currentPos + 1] == 0x80)
  402. {
  403. if (SampleBytes[currentPos + 2] == 0x93
  404. || SampleBytes[currentPos + 2] == 0x94
  405. )
  406. lengthFound = 3;
  407. if (SampleBytes[currentPos + 2] == 0x98
  408. || SampleBytes[currentPos + 2] == 0x99
  409. || SampleBytes[currentPos + 2] == 0x9A
  410. )
  411. lengthFound = 3;
  412. if (SampleBytes[currentPos + 2] == 0x9C
  413. || SampleBytes[currentPos + 2] == 0x9D
  414. || SampleBytes[currentPos + 2] == 0x9E
  415. )
  416. lengthFound = 3;
  417. if (SampleBytes[currentPos + 2] == 0xA0
  418. || SampleBytes[currentPos + 2] == 0xA1
  419. || SampleBytes[currentPos + 2] == 0xA2
  420. )
  421. lengthFound = 3;
  422. if (SampleBytes[currentPos + 2] == 0xA6)
  423. lengthFound = 3;
  424. if (SampleBytes[currentPos + 2] == 0xB0)
  425. lengthFound = 3;
  426. if (SampleBytes[currentPos + 2] == 0xB9
  427. || SampleBytes[currentPos + 2] == 0xBA
  428. )
  429. lengthFound = 3;
  430. }
  431. else if (SampleBytes[currentPos + 1] == 0x82
  432. && SampleBytes[currentPos + 2] == 0xAC
  433. )
  434. lengthFound = 3;
  435. else if (SampleBytes[currentPos + 1] == 0x84
  436. && SampleBytes[currentPos + 2] == 0xA2
  437. )
  438. lengthFound = 3;
  439. }
  440.  
  441. return lengthFound;
  442. }
  443.  
  444. }
  445. }
  1. Encoding fileEncoding = TextFileEncodingDetector.DetectTextFileEncoding("you file path",Encoding.Default);

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的C#相关文章