public static Encoding GetEncoding(StreamReader sr) { Encoding encoding = null; using (BinaryReader binaryReader = new BinaryReader(sr.BaseStream)) { byte[] array = binaryReader.ReadBytes(3); if (array.Length <= 0) { return(Encoding.UTF8); } if (array.Length >= 3) { if (array[0] == EncodingDetector._utf8Header[0] && array[1] == EncodingDetector._utf8Header[1] && array[2] == EncodingDetector._utf8Header[2]) { encoding = new Utf8EncodingIdentifier(true); } if (array[0] == EncodingDetector._unicodeHeader[0] && array[1] == EncodingDetector._unicodeHeader[1]) { encoding = Encoding.Unicode; } if (array[0] == EncodingDetector._unicodeBigHeader[0] && array[1] == EncodingDetector._unicodeBigHeader[1]) { encoding = Encoding.BigEndianUnicode; } if (array[0] == EncodingDetector._ansiHeader[0] && array[1] == EncodingDetector._ansiHeader[1] && array[2] == EncodingDetector._ansiHeader[2]) { //无BOM的UTF8可能也会被解析成GB2312 encoding = Encoding.GetEncoding("GB2312"); } } if (encoding != null) { return(encoding); } sr.BaseStream.Seek(0L, SeekOrigin.Begin); string charset = EncodingDetector.DetectStream(sr.BaseStream); if (charset == "nomatch") { charset = Encoding.Default.BodyName; } try { encoding = Encoding.GetEncoding(charset); } catch (Exception) { encoding = Encoding.Default; } } return(encoding); }
public static Encoding GetEncoding(string path) { Encoding encoding; using (StreamReader streamReader = new StreamReader(path, true)) { encoding = EncodingDetector.GetEncoding(streamReader); } return(encoding); }