【问题标题】:"SaveAs" Wordprocessingdocument (Open XML) file is locked“另存为”字处理文档 (Open XML) 文件被锁定
【发布时间】:2018-04-04 00:33:43
【问题描述】:

我有以下代码通过“SaveAs”将通过 OpenXML SDK 的 Word 文档保存到新文档中。然后我想尝试读取从 ASP.Net 创建的文件,但是我无法这样做,因为该文件被锁定并且在重新启动应用程序池之前不会被释放。

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

wordDoc 是通过 using 处理的,但我不确定如何释放对从“SaveAs”生成的文件的锁定,也不知道为什么在这种情况下它无论如何都会有文件锁定?

【问题讨论】:

  • using 只跟踪 using 语句中声明的元素的释放。在你的情况下wordDoc,所以第一次使用不会跟踪合并的文件。

标签: c# openxml-sdk


【解决方案1】:

你是如此亲密:

wordDoc.SaveAs(tempfileMerged).Close();

【讨论】:

    【解决方案2】:

    SaveAs确实返回了一个应该关闭的WordprocessingDocument的实例,将它存储在一个新变量中,然后调用它的close方法:

    WordprocessingDocument merged = wordDoc.SaveAs(tempfileMerged);
    merged.Close();
    

    编辑:您还可以嵌套第二个使用,例如。

    using (WordprocessingDocument merged = wordDoc.SaveAs(tempfileMerged))
    {
        merged.Close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多