C#中StreamReader读取中文出现乱码
来源:互联网 发布:广州php培训 编辑:程序博客网 时间:2024/05/01 21:41
有时在用C#中StreamReader读取中文时出现乱码
如:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Net;using System.Data.Sql;using System.Collections;using System.Data.SqlClient;using System.IO;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { try { FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read); StreamReader read = new StreamReader(fs); string str; while (read.Peek() != -1) { str = read.ReadLine(); Console.WriteLine(str); } read.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }}
原因是自Windows 2000之后的操作系统在文件处理时默认编码采用Unicode
所以.NET文件的默认编码也是Unicode。除非另外指定,StreamReader的默认编码为Unicode,
而不是当前系统的ANSI代码页。但是文档大部分还是以ANSI编码存储,中文文本使用的是GB2312,所以才造成中文乱码
所以在读取文本的时候要指定编码格式。
使用System.Text.Encoding.Defaul告诉StreamReader采用目前操作系统的编码即可。
如:
FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read); StreamReader read = new StreamReader(fs, Encoding.Default); string str; while (read.Peek() != -1) { str = read.ReadLine(); Console.WriteLine(str); } read.Close();
- C#中StreamReader读取中文出现乱码
- C#中StreamReader读取中文出现乱码
- C#中StreamReader读取中文出现乱码
- C#中StreamReader读取中文文本出现乱码的解决方法
- C#中StreamReader读取中文文本出现乱码的解决方法
- C#中StreamReader读取中文文本出现乱码的解决方法
- C#中StreamReader读取中文文本出现乱码的解决方法
- C#中StreamReader读取中文时出现乱码问题总结
- c#中StreamReader读写中文乱码解决方法
- c# 中StreamReader读写中文乱码
- 用StreamReader读取中文出现乱码的解决方案
- 解决StreamReader读取中文出现乱码的问题
- 用StreamReader读取中文出现乱码的解决方案
- C#中使用streamreader读取中文成乱码的解决方法
- 遇到问题-用StreamReader读取数据时出现乱码,streamwriter写入中文时出现乱码
- C# StreamReader 和 StreamWriter 读取和写入汉字出现乱码的解决方法。
- C# StreamReader 和 StreamWriter 读取和写入汉字出现乱码的解决方法。
- StreamReader读取文件时出现乱码的解决方案
- 17.1 学生成绩二进制处理
- safari下文本框关闭IME输入法的一些实现思路
- 地图分幅与编
- android socket传输
- QC 新建缺陷,如何定制缺陷描述模板
- C#中StreamReader读取中文出现乱码
- MySQL密码验证实现原理
- Android手机硬件信息Build
- Dom4j操作文档及使用案例
- C++中对象大小的问题
- tomcate + jndi 详细配置
- 自定义控件属性的一些特性
- QTP的基本使用方法(六步)
- Digester fails