4 c# text-files
如何使用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());
}
Run Code Online (Sandbox Code Playgroud)
您需要对文件使用正确的编码.你知道编码是什么吗?它可能是UTF-16,又名Encoding.Unicode,或者可能是Big5.真的,你应该尽力找出而不是猜测.
正如leppie的回答所提到的,问题也可能是控制台的功能.要确定,请将字符串的Unicode字符值转储为数字.有关更多信息,请参阅我关于调试unicode问题的文章以及转储字符串内容的有用方法.
我也会避免使用您当前用于逐行读取文件的代码.相反,使用类似的东西:
using (StreamReader sr = new StreamReader(path, appropriateEncoding))
{
string line;
while ( (line = sr.ReadLine()) != null)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
调用Peek()要求流能够搜索,这对于文件而不是所有流都可能是正确的.还要查看File.ReadAllText和File.ReadAllLines,如果这是你想要做的 - 它们是非常方便的实用方法.
如果是简体中文,通常是gb2312;对于繁体中文,通常是Big5:
// gb2312 (codepage 936) :
System.Text.Encoding.GetEncoding(936)
// Big5 (codepage 950) :
System.Text.Encoding.GetEncoding(950)Run Code Online (Sandbox Code Playgroud)