C# Windows 服务使用来自 MSDN "Find and Replace text in a Word document" 的 FlatDocument 示例保持文件锁定

C# Windows Service keeps file locked using FlatDocument an example from MSDN "Find and Replace text in a Word document"

我有一个 Windows 服务可以将文件复制到文件夹并替换 Word 文档中的文本。对于文档中的替换,我使用此代码:Find and Replace text in a Word document

问题是:这些文件一直在使用,直到我将下一个文件复制到另一个文件夹(并填写 Word 文档)。

我的搜索和替换代码如下所示:

using (var flatDocument = new FlatDocument(fullpath))
{
    flatDocument.FindAndReplace("ValueA", "ValueB");
    // Save document on Dispose.
}

如果我跳过此代码,服务运行良好,文件在复制后未被使用。为什么即使在 using 子句之后它仍然在使用? 也许有人有线索?

我认为 开发者中心 示例代码 Find and Replace text in a Word document.

中可能存在错误

简而言之,它通过不调用 FlatDocument FileStream FileStream [=36] 中的 Dispose 来保持 文件句柄 打开=].这看起来很奇怪,因为你会认为 Package.Dispose 会清理这个句柄,但它不会。

如果您修改 FlatDocument class 中的代码(正如我在下面所做的那样),它应该会修复它

在构造函数中

private Stream _stream; // Add this

public FlatDocument(Stream stream)
{
     if (stream == null)
     {
        throw new ArgumentNullException("stream");
     }

     _stream = stream; // Add this

     documents = XDocumentCollection.Open(stream);
     ranges = new List<FlatTextRange>();

     CreateFlatTextRanges();
}

处置中

public void Dispose()
  {
     documents.Dispose();
     _stream.Dispose(); // Add this
  }