简体   繁体   English

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

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

I have the following code to save a Word document via OpenXML SDK into a new document via "SaveAs". 我有以下代码通过“SaveAs”将OpenXML SDK的Word文档保存到新文档中。 I then want to try and read the file created from ASP.Net, however I am unable to do so as the file is locked and is not released until the app pool is restarted. 然后我想尝试读取从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); 
        }

The wordDoc is disposed via the using, but I'm not sure how to release the lock on the file generated from the "SaveAs", and am not sure why it would have file lock in this case in any event? wordDoc是通过使用处理的,但是我不知道如何释放对“SaveAs”生成的文件的锁定,并且我不确定为什么在这种情况下它会在任何情况下都有文件锁定?

You were so close: 你太近了:

wordDoc.SaveAs(tempfileMerged).Close(); wordDoc.SaveAs(tempfileMerged).Close();

The SaveAs does return an instance of a WordprocessingDocument that should be closed, store it in a new variable and then call its close method: SaveAs确实返回应该关闭的WordprocessingDocument实例,将其存储在新变量中,然后调用其close方法:

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

Edit: You could also nest a second using, something like. 编辑:您也可以使用类似的东西嵌套。

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

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

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