Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SaveAs" Wordprocessingdocument (Open XML) file is locked

Tags:

c#

openxml-sdk

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?

like image 355
Dean Avatar asked Apr 03 '18 14:04

Dean


2 Answers

You were so close:

wordDoc.SaveAs(tempfileMerged).Close();

like image 152
Travis Acton Avatar answered Oct 16 '22 15:10

Travis Acton


The SaveAsdoes 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();
}
like image 32
Cleptus Avatar answered Oct 16 '22 15:10

Cleptus