码迷,mamicode.com
首页 > 其他好文 > 详细

DetectEncoding

时间:2014-07-22 22:44:14      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   

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

标签:style   blog   color   os   io   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!