Search code examples
c#streamreader.net

How could I read a very large text file using StreamReader?


I want to read a huge .txt file and I'm getting a memory overflow because of its sheer size.

Any help?

    private void button1_Click(object sender, EventArgs e)
    {
        using (var Reader = new StreamReader(@"C:\Test.txt"))
        {
            textBox1.Text += Reader.ReadLine();
        }
    }

Text file is just:

Line1
Line2
Line3

Literally like that.

I want to load the text file to a multiline textbox just as it is, 100% copy.


Solution

  • Firstly, the code you posted will only put the first line of the file into the TextBox. What you want is this:

    using (var reader = new StreamReader(@"C:\Test.txt"))
    {
        while (!reader.EndOfStream)
            textBox1.Text += reader.ReadLine();
    }
    

    Now as for the OutOfMemoryException: I haven't tested this, but have you tried the TextBox.AppendText method instead of using +=? The latter will certainly be allocating a ton of strings, most of which are going to be nearly the length of the entire file by the time you near the end of the file.

    For all I know, AppendText does this as well; but its existence leads me to suspect it's put there to deal with this scenario. I could be wrong -- like I said, haven't tested personally.