简体   繁体   English

C#从文件到列表框逐行读取

[英]C# Reading line by line from file to listbox

I have a problem with reading text from file line by line. 我有一个问题,就是逐行从文件中读取文本。

System.IO.StreamReader file = new System.IO.StreamReader("ais.txt");
while ((line = file.ReadLine()) != null)
{
    listBox1.Items.Add(line);
}

This code only read last line from file and display in listbox. 此代码仅从文件读取最后一行并显示在列表框中。 How can I read line-by-line? 我怎样逐行阅读?

For example: read a line, wait 1 second, read another line, wait 1 second...ect.? 例如:读一行,等待1秒,读另一行,等待1秒......等等。

If you want to read lines one at a time with a one second delay, you can add a timer to your form to do this (set it to 1000): 如果您希望一次读取一行并延迟一秒,则可以向表单添加一个计时器来执行此操作(将其设置为1000):

System.IO.StreamReader file = new System.IO.StreamReader("ais.txt");
String line;
private void timer1_Tick(object sender, EventArgs e)
{
    if ((line = file.ReadLine()) != null)
    {
        listBox1.Items.Add(line);
    }
    else
    {
        timer1.Enabled = false;
        file.Close();
    }
}

You could also read the lines all at once and simply display them one at a time, but I was trying to keep this as close to your code as possible. 你也可以一次读取所有行,只需一次显示一行,但我试图尽可能地保持这一点。

await makes this very easy. await使这很容易。 We can just loop through all of the lines and await Task.Delay to asynchronously wait for a period of time before continuing, while still not blocking the UI thread. 我们可以循环遍历所有行并await Task.Delay异步等待一段时间再继续,同时仍然不阻塞UI线程。

public async Task DisplayLinesSlowly()
{
    foreach (var line in File.ReadLines("ais.txt"))
    {
        listBox1.Items.Add(line);
        await Task.Delay(1000);
    }
}

Have you tried File.ReadAllLines ? 你试过File.ReadAllLines吗? You can do something like this: 你可以这样做:

string[] lines = File.ReadAllLines(path);

foreach(string line in lines)
{
   listBox1.Items.Add(line);
}

You can read all lines and save to array string 您可以读取所有行并保存到数组字符串

  string[] file_lines = File.ReadAllLines("ais.txt");

and then read line by line by button click or use timer to wait 1 second 然后通过按钮单击逐行读取或使用计时器等待1秒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM