繁体   English   中英

“SaveAs”Wordprocessingdocument(Open XML)文件被锁定

[英]“SaveAs” Wordprocessingdocument (Open XML) file is locked

我有以下代码通过“SaveAs”将OpenXML SDK的Word文档保存到新文档中。 然后我想尝试读取从ASP.Net创建的文件,但是我无法这样做,因为文件被锁定并且在重新启动应用程序池之前不会释放。

        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(tempfile, true))
        {
            wordDoc.ChangeDocumentType(WordprocessingDocumentType.Document);

            Body body = wordDoc.MainDocumentPart.Document.Body;

            Paragraph para = body.AppendChild(new Paragraph());
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text("Testing"));

            wordDoc.SaveAs(tempfileMerged); 
        }

wordDoc是通过使用处理的,但是我不知道如何释放对“SaveAs”生成的文件的锁定,并且我不确定为什么在这种情况下它会在任何情况下都有文件锁定?

你太近了:

wordDoc.SaveAs(tempfileMerged).Close();

SaveAs确实返回应该关闭的WordprocessingDocument实例,将其存储在新变量中,然后调用其close方法:

WordprocessingDocument merged = wordDoc.SaveAs(tempfileMerged);
merged.Close();

编辑:您也可以使用类似的东西嵌套。

using (WordprocessingDocument merged = wordDoc.SaveAs(tempfileMerged))
{
    merged.Close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM