通过本文主要向大家介绍了马桶c的个人空间,c语言,欲情 c max,维生素c,奔驰c200等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
C#如何检测文本文件的编码,本文为大家分享了示例代码,具体内容如下
using System; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace KlerksSoft { public static class TextFileEncodingDetector { /* * Simple class to handle text file encoding woes (in a primarily English-speaking tech * world). * * - This code is fully managed, no shady calls to MLang (the unmanaged codepage * detection library originally developed for Internet Explorer). * * - This class does NOT try to detect arbitrary codepages/charsets, it really only * aims to differentiate between some of the most common variants of Unicode * encoding, and a "default" (western / ascii-based) encoding alternative provided * by the caller. * * - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and * Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a * heuristic - so the more of the file we can sample the better the guess. If you * are going to read the whole file into memory at some point, then best to pass * in the whole byte byte array directly. Otherwise, decide how to trade off * reliability against performance / memory usage. * * - The UTF-8 detection heuristic only works for western text, as it relies on * the presence of UTF-8 encoded accented and other characters found in the upper * ranges of the Latin-1 and (particularly) Windows-1252 codepages. * * - For more general detection routines, see existing projects / resources: * - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?) * - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx * - CharDet - Mozilla browser's detection routines * - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/ * - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse * * Copyright Tao Klerks, Jan 2010, tao@klerks.biz * Licensed under the modified BSD license: * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. 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 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements public static Encoding DetectTextFileEncoding(string InputFilename, Encoding DefaultEncoding) { using (FileStream textfileStream = File.OpenRead(InputFilename)) { return DetectTextFileEncoding(textfileStream, DefaultEncoding, _defaultHeuristicSampleSize); } } public static Encoding DetectTextFileEncoding(FileStream InputFileStream, Encoding DefaultEncoding, long HeuristicSampleSize) { if (InputFileStream == null) throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream"); if (!InputFileStream.CanRead) throw new ArgumentException("Provided file stream is not readable!", "InputFileStream"); if (!InputFileStream.CanSeek) throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream"); Encoding encodingFound = null; long originalPos = InputFileStream.Position; InputFileStream.Position = 0; //First read only what we need for BOM detection byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length]; InputFileStream.Read(bomBytes, 0, bomBytes.Length); encodingFound = DetectBOMBytes(bomBytes); if (encodingFound != null) { InputFileStream.Position = originalPos; return encodingFound; } //BOM Detection failed, going for heuristics now. // create sample byte array and populate it byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize]; Array.Copy(bomBytes, sampleBytes, bomBytes.Length); if (InputFileStream.Length > bomBytes.Length) InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length); InputFileStream.Position = originalPos; //test byte array content encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes); if (encodingFound != null) return encodingFound; else return DefaultEncoding; } public static Encoding DetectTextByteArrayEncoding(byte[] TextData, Encoding DefaultEncoding) { if (TextData == null) throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData"); Encoding encodingFound = null; encodingFound = DetectBOMBytes(TextData); if (encodingFound != null) { return encodingFound; } else { //test byte array content encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData); if (encodingFound != null) return encodingFound; else return DefaultEncoding; } } public static Encoding DetectBOMBytes(byte[] BOMBytes) { if (BOMBytes == null) throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes"); if (BOMBytes.Length < 2) return null; if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && (BOMBytes.Length < 4 || BOMBytes[2] != 0 || BOMBytes[3] != 0 ) ) return Encoding.Unicode; if (BOMBytes[0] == 0xfe && BOMBytes[1] == 0xff ) return Encoding.BigEndianUnicode; if (BOMBytes.Length < 3) return null; if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf) return Encoding.UTF8; if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76) return Encoding.UTF7; if (BOMBytes.Length < 4) return null; if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0) return Encoding.UTF32; if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff) return Encoding.GetEncoding(12001); return null; } public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes) { long oddBinaryNullsInSample = 0; long evenBinaryNullsInSample = 0; long suspiciousUTF8SequenceCount = 0; long suspiciousUTF8BytesTotal = 0; long likelyUSASCIIBytesInSample = 0;