无耐网上各种方法都有缺陷,此方法为原创,暂问发现问题。如发现请指正
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"); }
原文地址:https://www.cnblogs.com/nanfei/p/8963277.html
时间: 2024-10-29 17:54:57