今天在用c#读取txt文件,乱码了,用默认的编码不行,得用指定的编码才可以.因为每个文件的编码可能都不一样,有没有一种一劳永逸的方法,那肯定是有~自动判断文件的编码.下面就直接上代码了.

        public static Encoding GetEncoding(string filename)
        {
            try
            {
                return Encoding.GetEncoding(GetCharset(filename));
            }
            catch (Exception ex)
            {
                return Encoding.Default;
            }
        }

        public static string GetCharset(string filename)
        {
            using (var fs = File.OpenRead(filename))
            {
                Ude.CharsetDetector cdet = new Ude.CharsetDetector();
                cdet.Feed(fs);
                cdet.DataEnd();
                return cdet.Charset;                
            }
        }

得在VisualStudio的Nuget中安装UDE.CSharp即可.

C#自动获取判断txt文件编码 自动判断文件编码

以上就是【C#自动获取文件编码txt自动判断文件编码】的全部内容了,欢迎留言评论进行交流!

赞(1) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论