欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#检测文本文件编码的方法

程序员文章站 2022-11-24 07:59:22
c#如何检测文本文件的编码,本文为大家分享了示例代码,具体内容如下 using system; using system.text; using system...

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;
 
      //cycle through, keeping count of binary null positions, possible utf-8
      // sequences from upper ranges of windows-1252, and probable us-ascii
      // character counts.
 
      long currentpos = 0;
      int skiputf8bytes = 0;
 
      while (currentpos < samplebytes.length)
      {
        //binary null distribution
        if (samplebytes[currentpos] == 0)
        {
          if (currentpos % 2 == 0)
            evenbinarynullsinsample++;
          else
            oddbinarynullsinsample++;
        }
 
        //likely us-ascii characters
        if (iscommonusasciibyte(samplebytes[currentpos]))
          likelyusasciibytesinsample++;
 
        //suspicious sequences (look like utf-8)
        if (skiputf8bytes == 0)
        {
          int lengthfound = detectsuspiciousutf8sequencelength(samplebytes, currentpos);
 
          if (lengthfound > 0)
          {
            suspiciousutf8sequencecount++;
            suspiciousutf8bytestotal += lengthfound;
            skiputf8bytes = lengthfound - 1;
          }
        }
        else
        {
          skiputf8bytes--;
        }
 
        currentpos++;
      }
 
      //1: utf-16 le - in english / european environments, this is usually characterized by a
      // high proportion of odd binary nulls (starting at 0), with (as this is text) a low
      // proportion of even binary nulls.
      // the thresholds here used (less than 20% nulls where you expect non-nulls, and more than
      // 60% nulls where you do expect nulls) are completely arbitrary.
 
      if (((evenbinarynullsinsample * 2.0) / samplebytes.length) < 0.2
        && ((oddbinarynullsinsample * 2.0) / samplebytes.length) > 0.6
        )
        return encoding.unicode;
 
      //2: utf-16 be - in english / european environments, this is usually characterized by a
      // high proportion of even binary nulls (starting at 0), with (as this is text) a low
      // proportion of odd binary nulls.
      // the thresholds here used (less than 20% nulls where you expect non-nulls, and more than
      // 60% nulls where you do expect nulls) are completely arbitrary.
 
      if (((oddbinarynullsinsample * 2.0) / samplebytes.length) < 0.2
        && ((evenbinarynullsinsample * 2.0) / samplebytes.length) > 0.6
        )
        return encoding.bigendianunicode;
 
      //3: utf-8 - martin dürst outlines a method for detecting whether something can be utf-8 content
      // using regexp, in his w3c.org unicode faq entry:
      // http://www.w3.org/international/questions/qa-forms-utf-8
      // adapted here for c#.
      string potentiallymangledstring = encoding.ascii.getstring(samplebytes);
      regex utf8validator = new regex(@"\a("
        + @"[\x09\x0a\x0d\x20-\x7e]"
        + @"|[\xc2-\xdf][\x80-\xbf]"
        + @"|\xe0[\xa0-\xbf][\x80-\xbf]"
        + @"|[\xe1-\xec\xee\xef][\x80-\xbf]{2}"
        + @"|\xed[\x80-\x9f][\x80-\xbf]"
        + @"|\xf0[\x90-\xbf][\x80-\xbf]{2}"
        + @"|[\xf1-\xf3][\x80-\xbf]{3}"
        + @"|\xf4[\x80-\x8f][\x80-\xbf]{2}"
        + @")*\z");
      if (utf8validator.ismatch(potentiallymangledstring))
      {
        //unfortunately, just the fact that it can be utf-8 doesn't tell you much about probabilities.
        //if all the characters are in the 0-127 range, no harm done, most western charsets are same as utf-8 in these ranges.
        //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.
        // so, we need to play stats.
 
        // the "random" likelihood of any pair of randomly generated characters being one
        // of these "suspicious" character sequences is:
        // 128 / (256 * 256) = 0.2%.
        //
        // in western text data, that is significantly reduced - most text data stays in the <127
        // character range, so we assume that more than 1 in 500,000 of these character
        // sequences indicates utf-8. the number 500,000 is completely arbitrary - so sue me.
        //
        // we can only assume these character sequences will be rare if we also assume that this
        // is in fact western text - in which case the bulk of the utf-8 encoded data (that is
        // not already suspicious sequences) should be plain us-ascii bytes. this, i
        // arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield
        // approx 40%, so the chances of hitting this threshold by accident in random data are
        // very low).
 
        if ((suspiciousutf8sequencecount * 500000.0 / samplebytes.length >= 1) //suspicious sequences
          && (
              //all suspicious, so cannot evaluate proportion of us-ascii
              samplebytes.length - suspiciousutf8bytestotal == 0
              ||
              likelyusasciibytesinsample * 1.0 / (samplebytes.length - suspiciousutf8bytestotal) >= 0.8
            )
          )
          return encoding.utf8;
      }
 
      return null;
    }
 
    private static bool iscommonusasciibyte(byte testbyte)
    {
      if (testbyte == 0x0a //lf
        || testbyte == 0x0d //cr
        || testbyte == 0x09 //tab
        || (testbyte >= 0x20 && testbyte <= 0x2f) //common punctuation
        || (testbyte >= 0x30 && testbyte <= 0x39) //digits
        || (testbyte >= 0x3a && testbyte <= 0x40) //common punctuation
        || (testbyte >= 0x41 && testbyte <= 0x5a) //capital letters
        || (testbyte >= 0x5b && testbyte <= 0x60) //common punctuation
        || (testbyte >= 0x61 && testbyte <= 0x7a) //lowercase letters
        || (testbyte >= 0x7b && testbyte <= 0x7e) //common punctuation
        )
        return true;
      else
        return false;
    }
 
    private static int detectsuspiciousutf8sequencelength(byte[] samplebytes, long currentpos)
    {
      int lengthfound = 0;
 
      if (samplebytes.length >= currentpos + 1
        && samplebytes[currentpos] == 0xc2
        )
      {
        if (samplebytes[currentpos + 1] == 0x81
          || samplebytes[currentpos + 1] == 0x8d
          || samplebytes[currentpos + 1] == 0x8f
          )
          lengthfound = 2;
        else if (samplebytes[currentpos + 1] == 0x90
          || samplebytes[currentpos + 1] == 0x9d
          )
          lengthfound = 2;
        else if (samplebytes[currentpos + 1] >= 0xa0
          && samplebytes[currentpos + 1] <= 0xbf
          )
          lengthfound = 2;
      }
      else if (samplebytes.length >= currentpos + 1
        && samplebytes[currentpos] == 0xc3
        )
      {
        if (samplebytes[currentpos + 1] >= 0x80
          && samplebytes[currentpos + 1] <= 0xbf
          )
          lengthfound = 2;
      }
      else if (samplebytes.length >= currentpos + 1
        && samplebytes[currentpos] == 0xc5
        )
      {
        if (samplebytes[currentpos + 1] == 0x92
          || samplebytes[currentpos + 1] == 0x93
          )
          lengthfound = 2;
        else if (samplebytes[currentpos + 1] == 0xa0
          || samplebytes[currentpos + 1] == 0xa1
          )
          lengthfound = 2;
        else if (samplebytes[currentpos + 1] == 0xb8
          || samplebytes[currentpos + 1] == 0xbd
          || samplebytes[currentpos + 1] == 0xbe
          )
          lengthfound = 2;
      }
      else if (samplebytes.length >= currentpos + 1
        && samplebytes[currentpos] == 0xc6
        )
      {
        if (samplebytes[currentpos + 1] == 0x92)
          lengthfound = 2;
      }
      else if (samplebytes.length >= currentpos + 1
        && samplebytes[currentpos] == 0xcb
        )
      {
        if (samplebytes[currentpos + 1] == 0x86
          || samplebytes[currentpos + 1] == 0x9c
          )
          lengthfound = 2;
      }
      else if (samplebytes.length >= currentpos + 2
        && samplebytes[currentpos] == 0xe2
        )
      {
        if (samplebytes[currentpos + 1] == 0x80)
        {
          if (samplebytes[currentpos + 2] == 0x93
            || samplebytes[currentpos + 2] == 0x94
            )
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0x98
            || samplebytes[currentpos + 2] == 0x99
            || samplebytes[currentpos + 2] == 0x9a
            )
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0x9c
            || samplebytes[currentpos + 2] == 0x9d
            || samplebytes[currentpos + 2] == 0x9e
            )
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0xa0
            || samplebytes[currentpos + 2] == 0xa1
            || samplebytes[currentpos + 2] == 0xa2
            )
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0xa6)
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0xb0)
            lengthfound = 3;
          if (samplebytes[currentpos + 2] == 0xb9
            || samplebytes[currentpos + 2] == 0xba
            )
            lengthfound = 3;
        }
        else if (samplebytes[currentpos + 1] == 0x82
          && samplebytes[currentpos + 2] == 0xac
          )
          lengthfound = 3;
        else if (samplebytes[currentpos + 1] == 0x84
          && samplebytes[currentpos + 2] == 0xa2
          )
          lengthfound = 3;
      }
 
      return lengthfound;
    }
 
  }
}

使用方法:

encoding fileencoding = textfileencodingdetector.detecttextfileencoding("you file path",encoding.default);

以上就是本文的全部内容,希望对大家学习c#程序设计有所帮助。