C#根据字节数据byte[]前2位判断文本文件的Encoding编码格式
作者:C/S框架网|www.cscode.ne  发布日期:2021/01/18 17:14:31
  C#根据字节数据byte[]前2位判断文本文件的Encoding编码格式



C# Code:

/// <summary>
/// C#根据字节数据byte[]前2位判断文本文件的Encoding编码格式
/// </summary>
/// <param name="bs"></param>
/// <returns></returns>
public static System.Text.Encoding GetType(byte[] bs)
{
  Encoding result
= System.Text.Encoding.Default;
  
  
using (System.IO.MemoryStream fs = new MemoryStream(bs))
  {
    
using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs))
    {
      Byte[] buffer
= br.ReadBytes(2);
      
      
if (buffer[0] >= 0xEF)
      {
        
if (buffer[0] == 0xEF && buffer[1] == 0xBB)
        {
          result
= System.Text.Encoding.UTF8;
        }
        
else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
        {
          result
= System.Text.Encoding.BigEndianUnicode;
        }
        
else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
        {
          result
= System.Text.Encoding.Unicode;
        }
        
else
        {
          result
= System.Text.Encoding.Default;
        }
      }
      
else
      {
        result
= System.Text.Encoding.Default;
      }
      br.Close();
      br.Dispose();
      fs.Close();
      fs.Dispose();
    }
  }
  
  
return result;
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761





上一篇 下一篇