Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# read line from file with StreamReader with DownloadFileAsync

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");
}
like image 654
user1085907 Avatar asked Feb 24 '12 14:02

user1085907


4 Answers

Try :

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        sb.Append(sr.ReadLine());
    }
}
textbox.Text = sb.Tostring();
like image 137
Pranay Rana Avatar answered Oct 04 '22 11:10

Pranay Rana


If you want the text in the text box it would be much more effective to read all of it and then put it into the text box:

var lines = File.ReadAllLines("lastupdate.txt");
textBox1.Lines = lines; //assuming multi-line text box

or:

textBox1.Text = File.ReadAllText("lastupdate.txt");

Edit:

After latest update - you are downloading the file asynchronously - it might not even be there, only partially there or in a state in-between when your code executes.

If you just want the text string in the file don't download it, use DownloadString instead:

string text = "";
using (WebClient wc = new WebClient())
{
    text = wc.DownloadString(new Uri(Settings.Default.patchCheck));
}
textBox1.Text = text;
like image 29
BrokenGlass Avatar answered Oct 04 '22 11:10

BrokenGlass


Try this :

using(StreamReader reader = new StreamReader(Path))
{
    string line =  reader.ReadLine();

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

    reader.Close();
}
like image 35
Akrem Avatar answered Oct 04 '22 12:10

Akrem


Web Client has a rather bizarre DownloadFileAsync method. The return type is void, so it is not awaitable. Also, that means we do not even get a Task, so ContinueWith is not possible. That leaves us with using the DownloadFileCompleted event.

const string FileName = "lastupdate.txt";

private void DownloadLastUpdate() {
    var client = new WebClient();

    client.DownloadFileCompleted += ( s, e ) => {
        this.UpdateTextBox( e.Error );
        client.Dispose();
    };

    client.DownloadFileAsync( new Uri( Settings.Default.patchCheck ), FileName );
}

I went with an optional exception parameter to relay any exception messages. Feel free to refactor as desired. File.ReadLines yields text line by line, so large files should not use very much memory.

private void UpdateTextBox( Exception exception = null ) {
    textBox1.Text = string.Empty;

    if ( exception != null ) {
        textBox1.Text = exception.Message;
        return;
    }

    if ( !File.Exists( FileName ) ) {
        textBox1.Text = string.Format( "File '{0}' does not exist.", FileName );
        return;
    }

    var lines = File.ReadLines( FileName );

    textBox1.Text = string.Join( Environment.NewLine, lines );
}
like image 34
thestud2012 Avatar answered Oct 04 '22 12:10

thestud2012