Paweł Karczewski
Paweł Karczewski

Reputation: 1

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

Upvotes: 0

Views: 2448

Answers (4)

Servy
Servy

Reputation: 203802

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

Upvotes: 1

user27414
user27414

Reputation:

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.

Upvotes: 1

mnshahab
mnshahab

Reputation: 780

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

Upvotes: 0

duck
duck

Reputation: 857

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

Upvotes: 0

Related Questions