我在 C# 中创建了一个源代码,它获取 txt 文档的每一行并将其放入列表中。之后,我试图将它们显示在列表框中,但我得到了希腊字符的未知符号。这是我的代码:
public Form1()
{
InitializeComponent();
const string f = "TextFile1.txt";
// 1
// Declare new List.
List<string> lines = new List<string>();
// 2
// Use using StreamReader for disposing.
using (StreamReader r = new StreamReader(f))
{
// 3
// Use while != null pattern for loop
string line;
while ((line = r.ReadLine()) != null)
{
// 4
// Insert logic here.
// ...
// "line" is a line in the file. Add it to our List.
lines.Add(line);
}
}
// 5
// Print out all the lines.
foreach (string s in lines)
{
listBox1.Items.Add(s);
Console.WriteLine(s);
}
}
我的 TextFile1.txt :
您好! Γεία σου!
列表框中的结果是:
您好! ??? ???!
我如何让它接受希腊字符?
请您参考如下方法:
您需要在 StreamReader 的构造函数中明确指定编码,或者确保文件本身指定了正确的编码。如果不指定,StreamReader 将尝试自动检测文件的编码。
来自 http://msdn.microsoft.com/en-us/library/ms143456(v=vs.110).aspx :
The StreamReader object attempts to detect the encoding by looking at the first three bytes of the stream.
它检查文件的前 3 个字节,应该使用字节顺序标记指定编码,但如果文件中指定的编码错误,您可以使用 StreamReader 构造函数覆盖它。您还需要在 StreamReader 构造函数中指定选项,以便在字节顺序标记存在且不正确时不尝试读取它。参见 http://msdn.microsoft.com/en-us/library/akzyzwh9(v=vs.110).aspx。
