Reputation: 429
Here is a fragment of my code:
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;
}
The file in the outputPath location does not initially exist. It gets created in line 1. On line 8 it breaks - it says the file is being used.
I'm not where the error is. Any help would be appreciated.
Upvotes: 1
Views: 439
Reputation: 56536
You need to finish with the WordprocessingDocument
and let it close before trying to open the file. This ought to work:
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;
Upvotes: 3
Reputation: 142
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.
Upvotes: -1
Reputation: 48096
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.
Upvotes: 2