使用streamreader读取文本文件并在列表框中显示结果

时间:2018-10-22 17:38:23

标签: c# wpf

我在文本文件中有一些信息,我想阅读这些信息并显示在WPF的列表框中。这是文本文件中的内容:

First Name: ABC
Last Name: def
Mobile: 5453553535
email: abc@gmail.com

这是代码:

private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string text;
    FileStream aFile = new FileStream("D:\\PhoneBook.txt", FileMode.Open);
    StreamReader sr = new StreamReader(aFile);
    text = sr.ReadLine();
    // Read data in line by line.
    while (text != null)
    {
        foreach (string info in text.Split(',')) 
        {
            listView1.Items.Add(info);
        }       
    }
    sr.Close();
}

每次运行程序时,列表框都是空的并冻结。任何帮助,将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

您不会在循环内更新“文本”-您只需要添加text = sr.ReadLine();避免在那里的while循环永远持续下去!

也就是说,您可以只使用File.ReadAllLines()-https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netframework-4.7.2

答案 1 :(得分:0)

您需要在循环中添加一条阅读行:

private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string text;
    FileStream aFile = new FileStream("D:\\PhoneBook.txt", FileMode.Open);
    StreamReader sr = new StreamReader(aFile);
    text = sr.ReadLine();
    // Read data in line by line.
    while (text != null)
    {
        foreach (string info in text.Split(',')) 
        {
            listView1.Items.Add(info);
        }        
        // read the next line here
        text = sr.ReadLine();      
    }

    sr.Close();
}

但是更好的方法是:

while(!sr.EndOfStream)
{
    text = sr.ReadLine();
    // now write ...
}