Search code examples
c#openxml-sdkmemorystream

Generated file is still locked


I am using OpenXML SDK to generate and save a word document.

I am using a "Using" Block to create and dispose of the memory stream, and word document object when they are finished. However when trying to open to file i get the error that the file is still in use by another process. Looking at Resource Monitor i have been able to find that it is my c# application still keeping it open. When i close my application i can use the file

I have the following code.

private void button2_Click(object sender, EventArgs e)
{
    // Create Stream
    using (MemoryStream mem = new MemoryStream())
    {
        // Create Document
        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

            // Create the document structure and add some text.
            mainPart.Document = new Document();
            Body docBody = new Body();
            mainPart.Document.Append(docBody);
            wordDocument.SaveAs(@"E:\Report\word.docx");
            // Add your docx content here
            wordDocument.Close();
        }
    }
}

Am i correct in understanding that

using (MemoryStream mem = new MemoryStream())

should dispose of the MemoryStream when the block finishes, and therefore allow the file to be used by another process?

Thanks


Solution

  • SaveAs returns a new package object that represents the package stored in that file. You need to Close that package too.

    wordDocument.SaveAs(@"E:\Report\word.docx").Close();