C# 判断文件编码
无耐网上各种方法都有缺陷,此方法为原创,暂问发现问题。如发现请指正
public static Encoding GetFileEncodingByContent(string path) { var contentWithUTF8 = File.ReadAllText(path, Encoding.UTF8); var contentWithGBK = File.ReadAllText(path, Encoding.GetEncoding("GBK")); if (contentWithUTF8.Length < contentWithGBK.Length) return Encoding.UTF8; else if (contentWithUTF8.Length == contentWithGBK.Length) { using (var reader = new StreamReader(path, true)) { reader.Peek(); // you need this! return reader.CurrentEncoding; } } else return Encoding.GetEncoding("GBK"); }
桂棹兮兰桨,击空明兮溯流光。