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

在C#中使用StreamReader读取中文文件时,由于默认使用Unicode编码,可能导致中文显示为乱码。从Windows 2000开始,操作系统默认文件编码为Unicode,而许多文件仍以ANSI(如GB2312)存储中文。为避免乱码,需在读取时明确指定编码。解决方案是使用System.Text.Encoding.Default,确保按照操作系统默认编码进行读取。
摘要由CSDN通过智能技术生成

有时在用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();

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值