public class EncodingHelper
{
public static Encoding GetEncodingType(string fileName)
{
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader binary = new BinaryReader(fileStream, Encoding.Default);
byte[] bytes = binary.ReadBytes(3);
fileStream.Close();
if (bytes[0] >= 0xEF)
{
if (GetResult(bytes, 0, 0xEF) && GetResult(bytes, 1, 0xBB) && GetResult(bytes, 2, 0xBF))
{
return Encoding.UTF8;
}
else if (GetResult(bytes, 0, 0xFE) && GetResult(bytes, 1, 0xFF))
{
return Encoding.BigEndianUnicode;
}
else if (GetResult(bytes, 0, 0xFF) && GetResult(bytes, 1, 0xFE))
{
return Encoding.Unicode;
}
else
{
return Encoding.Default;
}
}
else
{
return Encoding.Default;
}
}
public static Encoding GetEncodingType(FileStream fileStream)
{
BinaryReader binary = new BinaryReader(fileStream, Encoding.Default);
byte[] bytes = binary.ReadBytes(3);
if (bytes[0] >= 0xEF)
{
if (GetResult(bytes, 0, 0xEF) && GetResult(bytes, 1, 0xBB) && GetResult(bytes, 2, 0xBF))
{
return Encoding.UTF8;
}
else if (GetResult(bytes, 0, 0xFE) && GetResult(bytes, 1, 0xFF))
{
return Encoding.BigEndianUnicode;
}
else if (GetResult(bytes, 0, 0xFF) && GetResult(bytes, 1, 0xFE))
{
return Encoding.Unicode;
}
else
{
return Encoding.Default;
}
}
else
{
return Encoding.Default;
}
}
public static bool GetResult(byte[] Value, int index, int judge)
{
return Value.Length > index ? Value[index] == judge : false;
}
}