首页 > 其他 > 详细

DetectEncoding

时间:2014-07-22 22:44:04      阅读:336      评论:0      收藏:0      [点我收藏+]
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;
        }

DetectEncoding,布布扣,bubuko.com

DetectEncoding

原文:http://www.cnblogs.com/Googler/p/3859932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!