我打算将一个word文档加载到一个富文本框中。
我有下面的代码。是的,这是可行的,但它需要很长的时间来装载。
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+页面文档需要foreer。
它可能与for循环有关。请帮助我提高速度。
发布于 2017-09-25 14:05:41
而不是
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
对于执行大量字符串操作的例程(例如在循环中多次修改字符串的应用程序),反复修改字符串可能会造成严重的性能损失。另一种方法是使用StringBuilder,它是一个可变的字符串类。可变性意味着一旦创建了类的实例,就可以通过追加、删除、替换或插入字符来修改该类。StringBuilder对象维护一个缓冲区以容纳对字符串的扩展。如果空间可用,则将新数据附加到缓冲区;否则,将分配一个新的更大的缓冲区,将原始缓冲区中的数据复制到新缓冲区,然后将新数据附加到新缓冲区。
https://stackoverflow.com/questions/46407092
复制相似问题