读取文件时出现中文乱码问题的解决

来源:互联网 发布:淘宝外围报名有用吗 编辑:程序博客网 时间:2024/05/02 02:09
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
最近有些朋友总是发现读取文件的时候发现乱码,不过用工具打开一看却是好的。
其实这个问题的罪魁祸首是VS.net的编辑器,在MS下一般文件编辑器(Notepad,ultraedit)都是使用操作系统缺省编码(不同的系统会不同),如在我的英文xp是ANSI,vs.net新建文件的保存以后使用的编码却是UTF8,大概是为了和StreamReader和StreamWriter打开文件缺省得encoding为UTF8保证一致的缘故吧。
  为什么我们用工具打开却是好的,那是因为MS的所有编辑器都会根据文件中使用的编码自动使用对应的编码打开文件。
  所以总结出来解决问题,首先要看得是这个文件的创建工具(注意是创建程序,而不是文件的缺省打开工具)是哪个在决定使用对应的Encoding打开文件,而不是盲目的尝试各种编码

针对一些windows工具创建的文件可以使用
StreamReader read = new StreamReader(filename, System.Text.Encoding.Default);

vs.net创建的文件可以使用
StreamReader read = new StreamReader(filename);

对于一些网络流如httpresponse的字节流,可以

解决';return true">
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>