0

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.?

Xfrogman43
  • 3
  • 2
  • 5

4 Answers4

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):

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.

Jon B
  • 51,025
  • 31
  • 133
  • 161
1

await makes this very easy. 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.

public async Task DisplayLinesSlowly()
{
    foreach (var line in File.ReadLines("ais.txt"))
    {
        listBox1.Items.Add(line);
        await Task.Delay(1000);
    }
}
Servy
  • 202,030
  • 26
  • 332
  • 449
0

Have you tried File.ReadAllLines? You can do something like this:

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

foreach(string line in lines)
{
   listBox1.Items.Add(line);
}
duck
  • 747
  • 14
  • 31
0

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

mnshahab
  • 770
  • 7
  • 16