StreamReader乱码问题

hongprogrammer 2009-04-10 12:17:39
class Program
{

static void Main(string[] args)
{
StreamReader file = new StreamReader("d:\\a.txt",Encoding.UTF8);

int a = 0;
try
{
a= file.Read();
while (a!=-1)
{
Console.WriteLine(Convert.ToString(a,16));
Console.WriteLine((char)a);
a = file.Read();
}

}
catch (Exception e) { Console.WriteLine(e.Message); }
}
}
这段程序输出为什么是
fffd
?
439
й
fffd
?
我始终不明白其中原理,请高手帮忙解决一下,谢谢
...全文
221 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
烈火蜓蜻 2009-04-10
  • 打赏
  • 举报
回复

class Program
{

static void Main(string[] args)
{
StreamReader file = new StreamReader("d:\\a.txt",Encoding.Default);

int a = 0;
try
{
a= file.Read();
while (a!=-1)
{
Console.WriteLine(Convert.ToString(a,16));
Console.WriteLine((char)a);
a = file.Read();
}

}
catch (Exception e) { Console.WriteLine(e.Message); }
}
}


文件的编码不是Utf-8,你用我上面写的试试
mykelly6 2009-04-10
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 tmxk2002 的回复:]
你写入的额时候不适用utf8写的,读的时候用这个读就可能乱码了
[/Quote]
对阿,你不确定写入的encoding的话最好读的时候不要指定
cja03 2009-04-10
  • 打赏
  • 举报
回复
"d:\\a.txt",Encoding.UTF8
----------------------------
保存的时候是否用UTF8保存?
  • 打赏
  • 举报
回复
你写入的额时候不适用utf8写的,读的时候用这个读就可能乱码了
机器人 2009-04-10
  • 打赏
  • 举报
回复
参考下面代码修改:

using System;
using System.IO;

class Test
{

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}

机器人 2009-04-10
  • 打赏
  • 举报
回复
参考下面代码修改:

using System;
using System.IO;

class Test
{

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}


111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧