Skip to main content
 首页 » 编程设计

c#之IIS使用OpenXML创建的word文件处置后继续被IIS锁定

2024年04月17日35pengyingh

我有一些带有 .docm 扩展名的单词模板,其中包含标记化标识符,这些标识符将被数据库中的实际值替换。

我正在加载模板,克隆它并将文档类型从模板更改为文档,然后将其作为新文档保存到磁盘:

string templateFilePath = @"C:\TempDoc\Template.docm"; 
 
using (WordprocessingDocument template = WordprocessingDocument.CreateFromTemplate(templateFilePath)) 
{ 
    using (WordprocessingDocument document = (WordprocessingDocument)template.Clone()) 
    { 
        document.ChangeDocumentType(WordprocessingDocumentType.Document); 
 
        document.SaveAs(@"C:\TempDoc\Template.docx"); 
    }    
} 

所有这一切都有效,但新创建的文件仍被 W3WP 进程锁定,然后无法读取并流出服务。

知道如何防止 IIS 保留此文件吗?

相同的代码可以在 LinqPad 中运行,一旦 using block 按预期超出范围,新文档就会立即解锁。

请您参考如下方法:

找到解决方法:

        File.Copy(templateFilePath, documentFilePath, true); 
        using (WordprocessingDocument document = WordprocessingDocument.Open(documentFilePath, true)) 
        { 
            document.ChangeDocumentType(WordprocessingDocumentType.Document); 

如果我不使用 Clone 和 SaveAs,这会留下锁,如果我复制模板,修改它并保存而不是 SaveAs,则不会维护锁。

谢谢!