【问题标题】:UWP - How to read in a text file?UWP - 如何读取文本文件?
【发布时间】: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")

标签: c# wpf uwp uwp-xaml


【解决方案1】:

ReadLine() 读取每一行。 当你设置 TextBox.Text=line;文本框将显示最后一行。 要在 TextBox 中显示所有行,您将附加每一行,如

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;
    }
}

对于列表框:

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)
    {
        listBox.Items.Add(line);
    }
}

或者更简单:

textBox.Text = File.ReadAllText("TestFile.txt");

listBox.ItemsSource = File.ReadAllLines("TestFile.txt");   

【讨论】:

  • 啊,明白了。非常感谢! File.ReadAllLines 非常有用且简单。
【解决方案2】:

显示 TextBox 中的最后一行,因为您在循环中每次都会覆盖它(Debug.WriteLine 将写入输出中的所有行,但在文本框中,您只会看到最后一行)。如果您想查看所有行,您可以更改代码,例如

TextBox.Text += line; 

更简单的方法是使用File.ReadAllText 方法。

【讨论】:

  • 谢谢,现在说得通了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 2019-12-20
  • 2013-01-04
  • 2011-02-16
相关资源
最近更新 更多