"SaveAs" Wordprocessingdocument (Open XML) file is locked
Asked Answered
U

2

9

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?

Unbeknown answered 3/4, 2018 at 14:55 Comment(1)
The using only tracks the release of the declared element in the using statement. In your case wordDoc, so the first using does not track The merged file.Tonnie
M
13

You were so close:

wordDoc.SaveAs(tempfileMerged).Close();

Mastiff answered 3/4, 2018 at 15:7 Comment(0)
T
8

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();
}
Tonnie answered 3/4, 2018 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.