c#读取.txt文件,中文乱码问题

onsailing 2004-03-24 10:21:49
我正在做读取文件的一个小东西,但从文本文件中读出的中文都是乱码,我用的是下列程序,请问该怎么解决
using (StreamReader sr = new StreamReader (file))
{
string text="";
String line;
char[] tempChars;
while ((line = sr.ReadLine()) != null)
{
byte[] msg=Encoding.Unicode.GetBytes(line);

Decoder uniDecoder = Encoding.Unicode.GetDecoder();
int charCount = uniDecoder.GetCharCount(msg, 0, msg.Length);
tempChars = new Char[charCount];
int charsDecodedCount = uniDecoder.GetChars(msg, 0, msg.Length, tempChars, 0);
foreach (Char c in tempChars)
{
Console.Write("[{0}]", c);
}

string temp=new string(tempChars);
System.Diagnostics.Debug.WriteLine(temp);
text+=temp;
}
arrayList.Add(text);

}
...全文
1686 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gaoch 2004-03-24
  • 打赏
  • 举报
回复
这个我刚做过:我也是和你一样,最后看帮助看到的:
System.IO.StreamReader st;
//从.txt中读文件
st=new System.IO.StreamReader(openFileDialog1.FileName,System.Text.Encoding.Default );
//将读出来的文本赋给文本框
richTextBox1.Text=st.ReadToEnd();
//关闭对象
st.Close ();
luaiping 2004-03-24
  • 打赏
  • 举报
回复
StreamReader sr = new StreamReader(_filePath,UnicodeEncoding.GetEncoding ("GB2312"));
suosuoyyy 2004-03-24
  • 打赏
  • 举报
回复
中文乱码的主要是你的txt文件编码和你的Encoding编码不一致,如:
txt为ANSI,则Encoding应取ASCII或者取GB2312,txt为Unicode则Encoding 应取Unicode,总之要一一对应才行
三杯倒 2004-03-24
  • 打赏
  • 举报
回复
byte[] -> Unicode -> 目標編碼
LilyKang 2004-03-24
  • 打赏
  • 举报
回复
StreamReader sr = new StreamReader (file,System.Text.Encoding.Default)
HNU 2004-03-24
  • 打赏
  • 举报
回复


StreamWriter srMyfile = new StreamWriter(fsMyfile,System.Text.Encoding.Default);
//System.Text.Encoding.Default 保证中文显示正确

110,538

社区成员

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

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

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