How can I add a huge line to a text box efficiently?

I have a massive string (we say 1,696,108 characters in length), which I read very quickly from a text file. When I add it to a text box (C #), this takes a lot of time. A program like Notepad ++ (unmanaged code, I know) can do this almost instantly, although Notepad also takes a lot of time. How can I effectively add this huge line and how does something like Notepad ++ do it so fast?

+4
source share
3 answers

The Notepad and TextBox classes are optimized for 64K text. You must use RichTextBox

+5
source

If it's Windows Forms, I would suggest trying RichTextBox as a replacement for your TextBox. I used to find this to be much more efficient when processing large text. Also, when making in-place changes, be sure to use the time-tested SelectionStart / SelectedText method instead of managing the Text property.

rtb.SelectionStart = rtb.TextLength; rtb.SelectedText = "inserted text"; // faster rtb.Text += "inserted text"; // slower 
+9
source

You could first display the first n characters that can be viewed in the user interface (assuming you have a scrollable text field). Then run a separate thread to asynchronously render sequential blocks.

Alternatively, you can combine it with your input stream from a file. Read the snippet and immediately add it to the text box. An example (not thorough, but you understand) ...

 private void PopulateTextBoxWithFileContents(string path, TextBox textBox) { using (var fs = File.OpenRead(path)) { using (var sr = new StreamReader(fs)) { while (!sr.EndOfStream) textBox.Text += sr.ReadLine(); sr.Close(); } fs.Close(); } } 
0
source

All Articles