【发布时间】:2021-10-03 20:15:23
【问题描述】:
我想知道在文本文件中读取的最佳方法是什么(短文本文件 5 行,每行带有人名),以便可以为文本框选择数据。 我正在尝试将结果显示到文本框或列表视图(或任何更好的视图)中,以便我可以选择其中一项显示到文本框中。
我使用 StreamReader 类作为指导,如下所示: https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-5.0
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Debug.WriteLine(line);
TextBox.Text=line;
}
}
我试过了,但只显示了文本文件的一行(最后一行)。 Debug.WriteLine(line) 显示所有行。
谢谢。
【问题讨论】:
-
listBox.ItemsSource = File.ReadAllLines("TestFile.txt")