C#根据字节数据byte[]前2位判断文本文件的Encoding编码格式
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
/// 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
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网