如何使用 C# 读取中文文本文件,我当前的代码无法显示正确的字符:
try
{
using (StreamReader sr = new StreamReader(path,System.Text.Encoding.UTF8))
{
// This is an arbitrary size for this example.
string c = null;
while (sr.Peek() >= 0)
{
c = null;
c = sr.ReadLine();
Console.WriteLine(c);
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
您需要对文件使用正确的编码。你知道那个编码是什么吗?它可能是 UTF-16,又名 Encoding.Unicode,或者可能是 Big5 之类的东西。实际上,您应该尝试确定而不是猜测。
正如leppie的回答所提到的,问题也可能是控制台的功能。为了确定这一点,请将字符串的 Unicode 字符值转储为数字。看我的关于调试 unicode 问题的文章 http://www.yoda.arachsys.com/csharp/debuggingunicode.html了解更多信息以及转储字符串内容的有用方法。
我还会避免使用您当前用于逐行读取文件的代码。相反,使用类似的东西:
using (StreamReader sr = new StreamReader(path, appropriateEncoding))
{
string line;
while ( (line = sr.ReadLine()) != null)
{
// ...
}
}
调用 Peek() 要求流能够查找,这对于文件可能是这样,但不是所有流。还查看文件.ReadAllText http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx and 文件.ReadAllLines http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx如果这就是您想要做的 - 它们是非常方便的实用方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)