当前位置 : 主页 > 网络编程 > net编程 >

C#打开文本文件避免乱码

来源:互联网 收集:自由互联 发布时间:2023-09-03
//传入文件名,返回utf8-string public string ReadAllFormatText(string filename) { byte[] bs = File.ReadAllBytes(filename); int len = bs.Length; if (len = 3 bs[0] == 0xEF bs[1] == 0xBB bs[2] == 0xBF) { return Encoding.UTF8.GetString(b
//传入文件名,返回utf8-string
        public string ReadAllFormatText(string filename)
        {
            byte[] bs = File.ReadAllBytes(filename);
            int len = bs.Length;
            if (len >= 3 && bs[0] == 0xEF && bs[1] == 0xBB && bs[2] == 0xBF)
            {
                return Encoding.UTF8.GetString(bs, 3, len - 3);
            }
            int[] cs = { 7, 5, 4, 3, 2, 1, 0, 6, 14, 30, 62, 126 };
            for (int i = 0; i < len; i++)
            {
                int bits = -1;
                for (int j = 0; j < 6; j++)
                {
                    if (bs[i] >> cs[j] == cs[j + 6])
                    {
                        bits = j;
                        break;
                    }
                }
                if (bits == -1)
                {
                    return Encoding.Default.GetString(bs);
                }
                while (bits-- > 0)
                {
                    i++;
                    if (i == len || bs[i] >> 6 != 2)
                    {
                        return Encoding.Default.GetString(bs);
                    }
                }
            }
            return Encoding.UTF8.GetString(bs);
        }
上一篇:JSON转换
下一篇:没有了
网友评论