private Encoding DetectEncoding(ref Stream stream) { if (_pageEncoding != null) { return _pageEncoding; } var memory = new MemoryStream(); stream.CopyTo(memory); memory.Position = 0L; var utf8 = Encoding.UTF8; var reader = new StreamReader(memory, utf8); string txt = reader.ReadToEnd(); memory.Position = 0L; stream = memory; if (!isLuan(txt)) { return utf8; } return Encoding.GetEncoding("gb2312"); } bool isLuan(string txt) { var bytes = Encoding.UTF8.GetBytes(txt); //239 191 189 for (var i = 0; i < bytes.Length; i++) { if (i < bytes.Length - 3) if (bytes[i] == 239 && bytes[i + 1] == 191 && bytes[i + 2] == 189) { return true; } } return false; }
原文地址:http://www.cnblogs.com/Googler/p/3859932.html