1

这是我的代码片段:

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 行它中断 - 它说文件正在被使用。

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

4

3 回答 3

3

在尝试打开文件之前,您需要完成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;
于 2013-04-19T17:55:24.017 回答
2

You are getting an error because the process which is writing to the file has an exclusive lock on it. You need to close output prior to trying to open it. Your second param in the Open call is saying you're opening for editing, apparently that is locking the file. You could move that code outside of the using statement which will automatically dispose of the lock.

于 2013-04-19T17:55:44.840 回答
-1

At line 3, you open the file to edit

WordprocessingDocument.Open(outputPath, true)

But at line 8, you try to open it again

new FileStream(outputPath, FileMode.Open, FileAccess.Read)

You can close your using before setting your response headers.

于 2013-04-19T17:56:10.473 回答