What is the fastest way to load text file into Ric

2020-06-21 04:32发布

I load text file into RichTextBox using OpenFIleDialog. But when a large amount of text is (for example song text about 50-70 lines) and I click OPEN program hangs for a few second (~3-5). Is it normal? Maybe there is some faster way or component to load text file? If my question is an inappropriate 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 guess maybe ReadAllLines impeds it?

4条回答
ゆ 、 Hurt°
2楼-- · 2020-06-21 05:08

There is a similar question that deals with the fastest way of reading/writing files: What's the fastest way to read/write to disk in .NET?

However, 50-70 lines is nothing.. no matter how you read, it should fly in immediately. Are you maybe reading from a network share or something else that is causing the delay?

Edit: Now that I see your code: Remove the loop and just write richTextBox1.Text = text; once. It doesn't make sense to assign the string in the loop since you already read the complete content of the file by using ReadAllText.

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string text = File.ReadAllText(openFileDialog1.FileName);
    richTextBox1.Text = text;
}
查看更多
劫难
3楼-- · 2020-06-21 05:12
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
}
查看更多
贪生不怕死
4楼-- · 2020-06-21 05:20
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
查看更多
手持菜刀,她持情操
5楼-- · 2020-06-21 05:26

Remove the for loop, because is useless:

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

text is a string that already contains all the text of the file to pass to the textBox.

Doing:

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

you're assigning the text read from the file text.Length-1 times (Length is the number of characters of the string) and that's useless.

查看更多
登录 后发表回答