当前位置: 移动技术网 > IT编程>开发语言>c# > C#如何自动识别文件的编码

C#如何自动识别文件的编码

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言

c#中识别文件的编码是一个头疼的问题,最近在做导入微信商户后台退款数据时,无论怎么设置编码导出来都是乱码,后来在网上找了这个识别文件编码的代码,感觉不错。最后识别出来是gb2312,看来我还是太渣了,只能吃土了,竟然忘记了这个编码。

下面话不多说,上代码。

/// <summary> 
 /// 用于取得一个文本文件的编码方式(encoding)。 
 /// </summary> 
 public class txtfileencoder
 {
  public txtfileencoder()
  {
   // 
   // todo: 在此处添加构造函数逻辑 
   // 
  }
  /// <summary> 
  /// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符,encoding.default将被返回。 
  /// </summary> 
  /// <param name="filename">文件名。</param> 
  /// <returns></returns> 
  public static encoding getencoding(string filename)
  {
   return getencoding(filename, encoding.default);
  }
  /// <summary> 
  /// 取得一个文本文件流的编码方式。 
  /// </summary> 
  /// <param name="stream">文本文件流。</param> 
  /// <returns></returns> 
  public static encoding getencoding(filestream stream)
  {
   return getencoding(stream, encoding.default);
  }
  /// <summary> 
  /// 取得一个文本文件的编码方式。 
  /// </summary> 
  /// <param name="filename">文件名。</param> 
  /// <param name="defaultencoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param> 
  /// <returns></returns> 
  public static encoding getencoding(string filename, encoding defaultencoding)
  {
   filestream fs = new filestream(filename, filemode.open);
   encoding targetencoding = getencoding(fs, defaultencoding);
   fs.close();
   return targetencoding;
  }
  /// <summary> 
  /// 取得一个文本文件流的编码方式。 
  /// </summary> 
  /// <param name="stream">文本文件流。</param> 
  /// <param name="defaultencoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param> 
  /// <returns></returns> 
  public static encoding getencoding(filestream stream, encoding defaultencoding)
  {
   encoding targetencoding = defaultencoding;
   if (stream != null && stream.length >= 2)
   {
    //保存文件流的前4个字节 
    byte byte1 = 0;
    byte byte2 = 0;
    byte byte3 = 0;
    byte byte4 = 0;
    //保存当前seek位置 
    long origpos = stream.seek(0, seekorigin.begin);
    stream.seek(0, seekorigin.begin);

    int nbyte = stream.readbyte();
    byte1 = convert.tobyte(nbyte);
    byte2 = convert.tobyte(stream.readbyte());
    if (stream.length >= 3)
    {
     byte3 = convert.tobyte(stream.readbyte());
    }
    if (stream.length >= 4)
    {
     byte4 = convert.tobyte(stream.readbyte());
    }
    //根据文件流的前4个字节判断encoding 
    //unicode {0xff, 0xfe}; 
    //be-unicode {0xfe, 0xff}; 
    //utf8 = {0xef, 0xbb, 0xbf}; 
    if (byte1 == 0xfe && byte2 == 0xff)//unicodebe 
    {
     targetencoding = encoding.bigendianunicode;
    }
    if (byte1 == 0xff && byte2 == 0xfe && byte3 != 0xff)//unicode 
    {
     targetencoding = encoding.unicode;
    }
    if (byte1 == 0xef && byte2 == 0xbb && byte3 == 0xbf)//utf8 
    {
     targetencoding = encoding.utf8;
    }
    //恢复seek位置   
    stream.seek(origpos, seekorigin.begin);
   }
   return targetencoding;
  }



  // 新增加一个方法,解决了不带bom的 utf8 编码问题 

  /// <summary> 
  /// 通过给定的文件流,判断文件的编码类型 
  /// </summary> 
  /// <param name="fs">文件流</param> 
  /// <returns>文件的编码类型</returns> 
  public static system.text.encoding getencoding(stream fs)
  {
   byte[] unicode = new byte[] { 0xff, 0xfe, 0x41 };
   byte[] unicodebig = new byte[] { 0xfe, 0xff, 0x00 };
   byte[] utf8 = new byte[] { 0xef, 0xbb, 0xbf }; //带bom 
   encoding reval = encoding.default;

   binaryreader r = new binaryreader(fs, system.text.encoding.default);
   byte[] ss = r.readbytes(4);
   if (ss[0] == 0xfe && ss[1] == 0xff && ss[2] == 0x00)
   {
    reval = encoding.bigendianunicode;
   }
   else if (ss[0] == 0xff && ss[1] == 0xfe && ss[2] == 0x41)
   {
    reval = encoding.unicode;
   }
   else
   {
    if (ss[0] == 0xef && ss[1] == 0xbb && ss[2] == 0xbf)
    {
     reval = encoding.utf8;
    }
    else
    {
     int i;
     int.tryparse(fs.length.tostring(), out i);
     ss = r.readbytes(i);

     if (isutf8bytes(ss))
      reval = encoding.utf8;
    }
   }
   r.close();
   return reval;

  }

  /// <summary> 
  /// 判断是否是不带 bom 的 utf8 格式 
  /// </summary> 
  /// <param name="data"></param> 
  /// <returns></returns> 
  private static bool isutf8bytes(byte[] data)
  {
   int charbytecounter = 1;  //计算当前正分析的字符应还有的字节数 
   byte curbyte; //当前分析的字节. 
   for (int i = 0; i < data.length; i++)
   {
    curbyte = data[i];
    if (charbytecounter == 1)
    {
     if (curbyte >= 0x80)
     {
      //判断当前 
      while (((curbyte <<= 1) & 0x80) != 0)
      {
       charbytecounter++;
      }
      //标记位首位若为非0 则至少以2个1开始 如:110xxxxx...........1111110x  
      if (charbytecounter == 1 || charbytecounter > 6)
      {
       return false;
      }
     }
    }
    else
    {
     //若是utf-8 此时第一位必须为1 
     if ((curbyte & 0xc0) != 0x80)
     {
      return false;
     }
     charbytecounter--;
    }
   }
   if (charbytecounter > 1)
   {
    throw new exception("非预期的byte格式!");
   }
   return true;
  }
 }

总结

以上就是c#自动识别文件编码的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网