Generated file is still locked

2865 views c#
7

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

answered question

The MemoryStream is not locking a file. Since it is a memory (not file) stream.

MemoryStream is a memory stream. It's a stream API on top of a byte[] array. It has nothing to do with files. If you have a locked file, it's because something keeps that file open. BTW you don't need that MemoryStream if you intend to save the document to a disk, you could have used the file path in the document constructor and remove SaveAs

1 Answer

0

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

posted this

Have an answer?

JD

Please login first before posting an answer.