简体   繁体   中英

“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". 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.

        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?

You were so 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:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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