C# read line from file with StreamReader with DownloadFileAsync

user1085907 picture user1085907 · Feb 24, 2012 · Viewed 84.5k times · Source

I am having a problem reading file with StreamReader and while line != null add to textBox1

Code:

using(StreamReader reader = new StreamReader("lastupdate.txt"))
{
    string line;

    while((line = reader.ReadLine()) != null)
    {
        textBox1.Text = line;
    }

    reader.Close();
}

It's not working and I don't know why. I tried to use using StreamReader, I download the file from the URL and I can see in the folder that the file is downloaded. The lastupdate.txt is 1KB in size.

This is my current working code with MessageBox. If I remove the MessageBox, the code doesn't work. It needs some kind of wait or I don't know:

WebClient client = new WebClient();

client.DownloadFileAsync(new Uri(Settings.Default.patchCheck), "lastupdate.txt"); // ok

if(File.Exists("lastupdate.txt"))
{
    MessageBox.Show("Lastupdate.txt exist");
    using(StreamReader reader = new StreamReader("lastupdate.txt"))
    {
        string line;

        while((line = reader.ReadLine()) != null)
        {
            textBox1.Text = line;
            MessageBox.Show(line.ToString());
        }

        reader.Close();
    }

    File.Delete("lastupdate.txt");
}

Answer

Pranay Rana picture Pranay Rana · Feb 24, 2012

Try :

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        sb.Append(sr.ReadLine());
    }
}
textbox.Text = sb.Tostring();