首页 > 解决方案 > 生成的文件仍然被锁定

问题描述

我正在使用 OpenXML SDK 生成并保存一个 word 文档。

我正在使用“使用”块来创建和处理内存流,以及完成后的 word 文档对象。但是,当尝试打开文件时,我收到该文件仍在被另一个进程使用的错误。查看资源监视器,我发现它是我的 c# 应用程序仍然保持打开状态。当我关闭我的应用程序时,我可以使用该文件

我有以下代码。

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

我的理解是否正确

using (MemoryStream mem = new MemoryStream())

应该在块完成时处理 MemoryStream,从而允许另一个进程使用该文件?

谢谢

标签: c#openxml-sdkmemorystream

解决方案


SaveAs返回一个的包对象,它表示存储在该文件中的包。你也需要Close那个包。

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

推荐阅读