Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Read in a large (150MB) text file into a Rich Text Box

I'm trying to read in a 150mb text file into a Rich Text box.

Currently, I am using a StreamReader to iterate through each line in the file, appending every line to a StringBuilder instance.

This works for smaller files, but I get a System.OutOfMemory exception when trying to read large files.

I don't see any problems with reading a 150mb file - there is plenty of physical memory and that's well within the Windows 32-bit application address space.

If anyone here has any idea how to do this, It would be greatly appreciated.

I'll attach my code at the end.

Thanks.

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(fileLocation))
{
   string line;
   while ((line = sr.ReadLine()) != null)
   {
      sb.AppendLine(line);
   }
    }

return sb;
like image 574
Joshua Lee Tucker Avatar asked Feb 29 '12 11:02

Joshua Lee Tucker


1 Answers

Use RichTextBox.LoadFile

http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.loadfile.aspx

I'm not sure why you would want to load the entire text to a StringBuilder. Alternatively you could pass a FileStream to LoadFile which would render the large file for you.

like image 170
abhilash Avatar answered Nov 03 '22 16:11

abhilash