将大文件加载到RichTextBox时的性能问题[关闭]

问题描述 投票:-3回答:2

记事本在一秒钟内打开一个文本文件(有20,000行),但是当我使用richtextbox1.LoadFile()File.ReadAllText()时,加载文件需要几分钟!怎么了?

c# .net
2个回答
1
投票

不是将文件读入数组然后返回该数组并将每个项目连接成单个字符串,而是使用Text方法将整个文件内容读入ReadAllText属性,该方法返回表示文本内容的字符串文件:

richTextBox1.Text = File.ReadAllText(path);

然而,结果好坏参半。这两种方法的表现相似,ReadLines + string.Join花费的时间往往更少。

这是我的测试应用程序:

public partial class Form1 : Form
{
    private const string FilePath = @"f:\private\temp\temp.txt";

    public Form1()
    {
        InitializeComponent();

        // Create a file with 20,000 lines
        var fileLines = new List<string>(20000);

        for (int i = 0; i < 20000; i++)
        {
            fileLines.Add($"This is line number {i + 1}.");
        }

        File.WriteAllLines(FilePath, fileLines);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Test loading with ReadAllText
        richTextBox1.Text = string.Empty;

        var sw = Stopwatch.StartNew();
        richTextBox1.Text = File.ReadAllText(FilePath);
        sw.Stop();

        Debug.WriteLine("ReadAllText = " + sw.ElapsedMilliseconds);
    }


    private void button2_Click(object sender, EventArgs e)
    {
        // Test loading with ReadLines and string.Join
        richTextBox1.Text = string.Empty;

        var sw = Stopwatch.StartNew();
        List<string> lines = new List<string>();
        lines.AddRange(File.ReadAllLines(FilePath));         
        richTextBox1.Text = string.Join(Environment.NewLine, lines);
        sw.Stop();

        Debug.WriteLine("ReadLines + string.Join = " + sw.ElapsedMilliseconds);
    }
}

首先执行ReadAllText时的结果(以毫秒为单位)

ReadAllText = 157
ReadLines + string.Join = 143

首先执行ReadLines时的结果(以毫秒为单位)

ReadLines + string.Join = 160
ReadAllText = 152

0
投票

如果您正在读取Rtf文件,您应该尝试让控件执行工作。这是微软关于控制的文档的摘录,在这里找到https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox?view=netframework-4.7.2

public void CreateMyRichTextBox()
{
    RichTextBox richTextBox1 = new RichTextBox();
    richTextBox1.Dock = DockStyle.Fill;


    richTextBox1.LoadFile("C:\\MyDocument.rtf");
    richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);

    richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
    richTextBox1.SelectionColor = Color.Red;

    richTextBox1.SaveFile("C:\\MyDocument.rtf", RichTextBoxStreamType.RichText);

    this.Controls.Add(richTextBox1);
}

如果这不能提高性能,您可能需要查看通过Lines属性异步加载数据(请参阅https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.textboxbase.lines?view=netframework-4.7.2)。

© www.soinside.com 2019 - 2024. All rights reserved.