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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With