gpt4 book ai didi

c# 将 .docx 文件加载到 richtextbox 中花费的时间太长

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:34 26 4
gpt4 key购买 nike

我打算将 word 文档加载到 richtextbox 中。

我有以下代码。是的,它正在工作,但它需要很长时间才能加载。

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Word Documents|*.doc; *.docx";

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = ofd.FileName;
object readOnly = true;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly,
ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss);
string totaltext = "";


for (int i = 0; i < docs.Paragraphs.Count; i++)
{
totaltext += "\t " + docs.Paragraphs[i + 1].Range.Text.ToString();
}

richTextBox1.Text = totaltext;
}

加载一个 3 页的测试文档大约需要 2 分钟,而加载一个 60 多页的文档则需要大约 2 分钟。

可能与for循环有关。请帮助我提高速度。

最佳答案

代替

string totaltext = "";

for (int i = 0; i < docs.Paragraphs.Count; i++)
{
totaltext += "\t " + docs.Paragraphs[i + 1].Range.Text.ToString();
}

richTextBox1.Text = totaltext;

使用这个:

var totaltextBuilder = new StringBuilder();

for (int i = 0; i < docs.Paragraphs.Count; i++)
{
totaltextBuilder.Append("\t " + docs.Paragraphs[i + 1].Range.Text.ToString());
}

richTextBox1.Text = totaltextBuilder.ToString();

来自 MSDN :

For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. The alternative is to use StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. A StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.

关于c# 将 .docx 文件加载到 richtextbox 中花费的时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com