Skip to main content
 首页 » 编程设计

c#之文件已打开,但不确定何时关闭

2024年02月13日13telwanggs

这是我的代码片段:

System.IO.File.Copy(templatePath, outputPath, true); 
 
using(var output = WordprocessingDocument.Open(outputPath, true)) 
{ 
    Body updatedBodyContent = new Body(newWordContent.DocumentElement.InnerXml); 
    output.MainDocumentPart.Document.Body = updatedBodyContent; 
    output.MainDocumentPart.Document.Save(); 
    response.Content = new StreamContent( 
        new FileStream(outputPath, FileMode.Open, FileAccess.Read)); 
 
    response.Content.Headers.ContentDisposition = 
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
    response.Content.Headers.ContentDisposition.FileName = outputPath; 
} 

outputPath 位置中的文件最初并不存在。它在第 1 行创建。在第 8 行中断 - 它表示文件正在使用中。

我不是错误所在。任何帮助将不胜感激。

请您参考如下方法:

您需要完成 WordprocessingDocument 并在尝试打开文件之前让它关闭。这应该有效:

System.IO.File.Copy(templatePath, outputPath, true); 
 
using (WordprocessingDocument output =  
       WordprocessingDocument.Open(outputPath, true)) 
{ 
    Body updatedBodyContent =  
        new Body(newWordContent.DocumentElement.InnerXml); 
    output.MainDocumentPart.Document.Body = updatedBodyContent; 
    output.MainDocumentPart.Document.Save(); 
} 
response.Content = new StreamContent(new FileStream(outputPath,  
                                                    FileMode.Open,  
                                                    FileAccess.Read)); 
response.Content.Headers.ContentDisposition =  
    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
 
response.Content.Headers.ContentDisposition.FileName = outputPath;