7

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");
}
CaptainBli
  • 4,121
  • 4
  • 39
  • 58
user1085907
  • 1,009
  • 2
  • 16
  • 40
  • 1
    textBox1.Text = text ? textBox1.Text += line ? – shenhengbin Feb 24 '12 at 14:13
  • you are sure that while was executed and the reader have value ? – Akrem Feb 24 '12 at 15:47
  • What u mean? lastupdate.txt contain data "1" just number... – user1085907 Feb 24 '12 at 16:15
  • Since you are downloading `Async`, the rest of the code will basically be skipped. `if(File.Exists)` will be false because the file won't be there yet or is being used by the download thread. This is why you don't get anything in your textbox. You need to set up an event handler to work with the Ansyc request. When you pause the execution of your code with the MessageBox, you are allowing the file to completely download. – CaptainBli Aug 20 '14 at 14:18
  • maybe try `while (!reader.EndOfStream)` and after that assign `ReadLine()` value ? – Muflix Dec 02 '16 at 13:30

5 Answers5

13

Try :

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        sb.Append(sr.ReadLine());
    }
}
textbox.Text = sb.Tostring();
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
7

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;
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    what if the file is really really big? – wal Feb 24 '12 at 14:14
  • 1
    Then the original version is even worse since the UI will be swamped with update requests (even if the reading is done on a background thread). If it is really big, reading the text should be done on a background thread as well. – BrokenGlass Feb 24 '12 at 14:16
  • 4
    @wal: if the file is big, then the probleme with the textbox to contain all lines and the idea of the question is wrong – Akrem Feb 24 '12 at 14:19
  • 1
    thats great that you agree Akrem @Ravia, how about upticking his comment instead of posting your own useless comment. i think its worth mentioning in the answer as a disclaimer, ie 'if your file isn't large then this solution is nice' – wal Feb 24 '12 at 14:28
  • what if the file is really really big? Isn't 1kb – user1085907 Feb 24 '12 at 14:38
  • @user1085907: Based on your example this *should* work - what exactly is not working? – BrokenGlass Feb 24 '12 at 15:17
  • You have to provide a little more detail on why that is happening - did you step through the code with a debugger? Is the file name correct? Is it reading the file data? Are you assigning to the right textbox? No one will be able to provide you with more detail and solve your problem for you - work on it. – BrokenGlass Feb 24 '12 at 15:39
  • hmmm when in my code i enter while, it freeze or some like that with after code – user1085907 Feb 24 '12 at 16:07
  • There shouldn't be any while loop with the code I showed - it fully replaces your sample – BrokenGlass Feb 24 '12 at 16:09
  • in 4.0 ReadLines is better than ReadAllLines. – amalgamate Dec 11 '14 at 14:15
3

Try this :

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

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

    reader.Close();
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Akrem
  • 5,033
  • 8
  • 37
  • 64
1

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 );
}
thestud2012
  • 69
  • 1
  • 3
0

the answer given above is correct, but in your piece of code, just change 1 line:

textBox1.Text += line;
mindandmedia
  • 6,800
  • 1
  • 24
  • 33