StreamReader 读取文本文件乱码问题
解决读取文本文件乱码问题。我采取的是读取前先判断文本文件格式。
StreamReader sr = new StreamReader(fullfileName, GetFileEncodeType(fullfileName))
public System.Text.Encoding GetFileEncodeType(string filename) { System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); 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) { return System.Text.Encoding.UTF8; } else if (buffer[0] == 0xFE && buffer[1] == 0xFF) { return System.Text.Encoding.BigEndianUnicode; } else if (buffer[0] == 0xFF && buffer[1] == 0xFE) { return System.Text.Encoding.Unicode; } else { return System.Text.Encoding.Default; } } if (buffer[0] == 0x3c)//utf-8无bom格式 { return System.Text.Encoding.UTF8; } else { return System.Text.Encoding.Default; } }