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.
Firstly, the code you posted will only put the first line of the file into the
TextBox. What you want is this:Now as for the
OutOfMemoryException: I haven’t tested this, but have you tried theTextBox.AppendTextmethod 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,
AppendTextdoes 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.