记事本在一秒钟内打开文本文件(带有20,000行),但是当我使用 richtextbox1.LoadFile()
或 File.ReadAllText()
时,加载文件需要几分钟!怎么了?
,而不是将文件读取到数组中,然后返回该数组并将每个项目连接到一个字符串中,只需使用ReadAllText
方法将整个文件内容读取到Text
属性中,返回一个表示文本文件内容的字符串:
richTextBox1.Text = File.ReadAllText(path);
但是,结果混合了。两种方法都执行类似,ReadLines
string.Join
花费更少的时间多。
这是我的测试应用程序:
public partial class Form1 : Form
{
private const string FilePath = @"f:privatetemptemp.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
如果您是从RTF文件读取的,则应该尝试让控件完成工作。这是Microsoft在控件上的文档中的摘录,此处可以找到https://learn.microsoft.com/en-us/dotnet/api/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);
}
如果这不能提高性能,则可能需要查看异步通过线路属性加载数据(请参阅https://learn.microsoft.com/en-us/dotnet/potnet/api/api/system.windows.forms.textboxboxboxboxbasebase.lines?view = netFramework-4.7.2)。