c# 获取文件编码
在c#编程中怎样获取未知文档的编码方式
没有直接的方法,只能通过判断前面几个字节来实现
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文件文档|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;
FileInfo file = new FileInfo(fileName);
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);
byte[] b = reader.ReadBytes(3);
string s = "";
for (int i = 0; i < b.Length; i++)
{
s += Convert.ToInt32(b[i].ToString()).ToString("X");
}
reader.Close();
if (s.Contains("EFBBBF"))
MessageBox.Show("UTF - 8");
else if (s.Contains("FFFE"))
MessageBox.Show("Unicode");
else if (s.Contains("FEFF"))
MessageBox.Show("Unicode big endian");
else
MessageBox.Show("ANSI");
}
}
前面三种编码是有规律的,ANSI找不出规律来