日期:2014-05-18  浏览次数:20842 次

看下这个字符编码问题
我在我的h:盘下建立了一个文本文档 并在里面输入了几个汉字:“看看编码”
  我存为了.txt格式 应该是ansi编码吧
  后来我想看乱码 就建立了一个控制台小程序
  using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace 编码
{
  class Program
  {
  static void Main(string[] args)
  {
   
  string a = File.ReadAllText(@"H:\encoding.txt",Encoding.UTF8);
  string b = File.ReadAllText(@"H:\encoding.txt", Encoding.UTF7);
  string c= File.ReadAllText(@"H:\encoding.txt",Encoding.GetEncoding("GB2312"));
  Console.Write(a);
  Console.Write(b);
  Console.Write(c);
   
  }
  }
}
都是正常显示 没有出现乱码 这事为啥啊
 

------解决方案--------------------
是这样的,因为txt文档的开头是有一串字符来表示文件是用什么方式编码的,我大致看了下源码,发现File.ReadAllText这个方法仍然是要调用StreamReader里面的方法,他首先判断的是文档的编码方式,如果解析不了才会用你指定的encoding方式。下面这段话摘自StreamReader类的说明:
Note that detectEncodingFromByteOrderMarks is a very
loose attempt at detecting the encoding by looking at the first 
3 bytes of the stream. It will recognize UTF-8, little endian
unicode, and big endian unicode text, but that's it. If neither
of those three match, it will use the Encoding you provided.