【发布时间】:2018-08-28 07:19:29
【问题描述】:
使用 c# 和 Interop Word 我试图将指定目录中的所有文件合并到一个新文档中。我的代码遍历文件名列表并使用“InsertFile”将每个文件名添加到选择中。
文件很多,一段时间后进程失败。错误信息如下:
磁盘已满。释放此驱动器上的一些空间,或将文档保存在另一个磁盘上。
尝试以下一项或多项:
- 关闭所有不需要的文档、程序和窗口。
- 将文档保存在另一个磁盘上。”
在 InsertFile 失败时,选择使用了大约 7MB。我的磁盘有 300GB 的可用空间,机器有 32GB 的 RAM。
我保存的文件中没有任何图形或数学。
我做错了什么?在 foreach 循环内的 InsertFile 行(如下)引发了异常。
代码稍后会出现。请注意,我从一个 winword 实例开始,它是一个名为 PrintObj 的类的成员。另外,请注意,如果我将它用于少量文件(例如 100-200),则此代码可以正常工作。
Document mergeDoc = PrintObj.WinWord.Documents.Add(ref missing, ref missing,
ref missing, ref missing);
mergeDoc.PageSetup.LeftMargin = globalPrintObj.WinWord.InchesToPoints(0.5f);
mergeDoc.PageSetup.RightMargin =
PrintObj.WinWord.InchesToPoints(0.5f);
string[] filePaths = Directory.GetFiles(directoryPath, "*.docx");
string[] documentsToMerge = filePaths;
Array.Sort(documentsToMerge);
// Make a Word selection object.
Selection selection = PrintObj.WinWord.Selection;
//A counter that signals that we shoudn't insert a page break at the end of
document.
int breakStop = 0;
//Count the number of documents to insert;
int documentCount = documentsToMerge.Length;
// Loop thru each of the Word documents
foreach (string file in documentsToMerge)
{
breakStop++;
// Insert the files to our template
selection.InsertFile(file, ref missing, ref missing, ref missing,
ref missing);
if (breakStop != documentCount)
{
selection.InsertBreak(ref pageBreak);
}
}
Directory.CreateDirectory(directoryPath);
//Save the document
obj wordFileName = fileNameWithExtension;
mergeDoc.SaveAs2(ref wordFileName);
【问题讨论】:
-
Word 将所有更改写入“临时文件”,部分原因是为了维护其撤消列表。如果这些超过一定大小,您可能会收到您所看到的错误。有两件事可以提供帮助,将它们构建到您的代码中以间隔执行(例如,通过循环 n 次):1)
mergedoc.UndoClear()和mergeDoc.Save(ref oTrue, ref missing);