C#中StreamReader读取中文出现乱码

有时在用C#中StreamReader读取中文时出现乱码

如:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.Net;  
  7. using System.Data.Sql;  
  8. using System.Collections;  
  9. using System.Data.SqlClient;  
  10. using System.IO;  
  11. using System.Diagnostics;  
  12.   
  13.   
  14. namespace ConsoleApplication1  
  15. {  
  16.     class Program  
  17.     {  
  18.         static void Main(string[] args)  
  19.         {  
  20.             try  
  21.             {  
  22.                 FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read);  
  23.                 StreamReader read = new StreamReader(fs);  
  24.                 string str;  
  25.                 while (read.Peek() != -1)  
  26.                 {  
  27.                     str = read.ReadLine();  
  28.                     Console.WriteLine(str);  
  29.                 }  
  30.                 read.Close();  
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 Console.WriteLine(ex.Message);  
  35.             }  
  36.         }  
  37.     }  
  38. }  



原因是自Windows 2000之后的操作系统在文件处理时默认编码采用Unicode

所以.NET文件的默认编码也是Unicode。除非另外指定,StreamReader的默认编码为Unicode,

而不是当前系统的ANSI代码页。但是文档大部分还是以ANSI编码存储,中文文本使用的是GB2312,所以才造成中文乱码

所以在读取文本的时候要指定编码格式。


使用System.Text.Encoding.Defaul告诉StreamReader采用目前操作系统的编码即可。

如:

[csharp]  view plain  copy
  1. FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read);  
  2.                StreamReader read = new StreamReader(fs, Encoding.Default);  
  3.                string str;  
  4.                while (read.Peek() != -1)  
  5.                {  
  6.                    str = read.ReadLine();  
  7.                    Console.WriteLine(str);  
  8.                }  
  9.                read.Close();  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值