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");
            
        }

 

posted on 2018-04-27 16:48  空明流光  阅读(215)  评论(0编辑  收藏  举报

导航