I need to load a ~ 10MB range text file into a WPF RichTextBox, but my current code is freezing up the UI. I tried making a background worker do the loading, but that doesnt seem to work too well either.
Here's my loading code. Is there any way to improve its performance? Thanks.
//works well for small files only
private void LoadTextDocument(string fileName, RichTextBox rtb)
{
System.IO.StreamReader objReader = new StreamReader(fileName);
if (File.Exists(fileName))
{
rtb.AppendText(objReader.ReadToEnd());
}
else rtb.AppendText("ERROR: File not found!");
objReader.Close();
}
//background worker version. doesnt work well
private void LoadBigTextDocument(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
System.IO.StreamReader objReader = new StreamReader( ((string[])e.Argument)[0] );
StringBuilder sB = new StringBuilder("For performance reasons, only the first 1500 lines are displayed. If you need to view the entire output, use an external program.\n", 5000);
int bigcount = 0;
int count = 1;
while (objReader.Peek() > -1)
{
sB.Append(objReader.ReadLine()).Append("\n");
count++;
if (count % 100 == 0 && bigcount < 15)
{
worker.ReportProgress(bigcount, sB.ToString());
bigcount++;
sB.Length = 0;
}
}
objReader.Close();
e.Result = "Done";
}