What is the fastest way to load a text file into a RichTextBox?

Upload a text file to RichTextBox using OpenFIleDialog. But when a large amount of text (for example, the lyrics of the song is about 50-70 lines), and I press the OPEN button, freezes for several seconds (~ 3-5). This is normal? Maybe there is some faster way or component to load a text file? If my question does not fit, just delete it. Thanx.

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string text = File.ReadAllText(openFileDialog1.FileName); for (int i = 0; i < text.Length - 1; i++) { richTextBox1.Text = text; } } 

I think maybe ReadAllLines preventing this?

+4
source share
4 answers

There is a similar question regarding the fastest way to read / write files: What is the fastest way to read / write to disk in .NET?

However, 50-70 lines is nothing. No matter how you read it should fly immediately. Perhaps you are reading from a network folder or something else that causes a delay?

Edit: Now that I see your code: Delete the loop and just write richTextBox1.Text = text; once. It makes no sense to assign a line in a loop since you have already read the full contents of the file using ReadAllText .

 if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string text = File.ReadAllText(openFileDialog1.FileName); richTextBox1.Text = text; } 
+8
source
 void LoadFileToRTB(string fileName, RichTextBox rtb) { rtb.LoadFile(File.OpenRead(fileName), RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you // or rtb.LoadFile(fileName); // or rtb.LoadFile(fileName, RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you } 
+5
source

Delete the for loop because it is useless:

 string text = File.ReadAllText(openFileDialog1.FileName); richTextBox1.Text = text; 

text is a string that already contains all the text in the file to be sent to the text block.

Doing:

 for(int i=0, i < text.Lengt-1; i++) richTextBox1.Text = text; 

you assign the text read from the text.Length-1 times file ( Length is the number of characters of the string), and it is useless.

+2
source
 if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName); } 
0
source

Source: https://habr.com/ru/post/1343892/


All Articles