请教个问题,我写的一段C#代码读取文本文件,为什么读出来是乱码?

来源:百度知道 编辑:UC知道 时间:2024/06/15 05:31:15
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = @"E:\学习资料区\代码\C#\十二章\读取文件内容\品格教育.txt";

try
{
if (!File.Exists(path))
{
Console.WriteLine("该文件不存在!");
}
else
{
FileStream fs = File.OpenRead(path);

byte[] cont = new byte[1000];
UTF8Encoding ue = new UTF8Encoding(true);

while (fs.Read(cont, 0, cont.Length) > 0)
{
Console.WriteLine(ue.GetString(cont));
}

UTF8Encoding不行的,要用GB2312中文编码,就行了
另外用
StreamReader sr = new StreamReader(path,Encoding.GetEncoding("GB2312"));
来读取文件 他的编码支持比 FileStream 好

那是因为你的文件是用ASC码的编码格式,而你读取的确实UTF-8的格式,所以是乱码。