我从OpenXML的MemoryStream出现问题。我成功地打开了一个Word文件,通过HttpResponse进行更改并下载它,如果我使用单一方法完成所有步骤的话。C#从OpenXML返回内存流导致损坏的Word文件
但是,如果我试图通过返回MemoryStream在两个不同的类(或方法)中做到这一点,我得到一个损坏的word文件。我想过冲洗或缓冲区问题,但我找不到解决方案。
这里是工作代码:
public void FillTemplateOpenXmlWord(HttpResponse response)
{
string filePath = @"c:\template.docx";
byte[] filebytes = File.ReadAllBytes(filePath);
using (MemoryStream stream = new MemoryStream(filebytes))
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
// do some changes
...
myDoc.MainDocumentPart.Document.Save();
}
string docx = "docx";
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", "attachment; filename=\"" + docx + ".docx\"");
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Position = 0;
stream.CopyTo(response.OutputStream);
response.End();
}
}
这里的非工作代码:
public void OpenFile(HttpResponse response)
{
MemoryStream stream = this.FillTemplateOpenXmlWord();
string docx = "docx";
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", "attachment; filename=\"" + docx + ".docx\"");
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Position = 0;
stream.CopyTo(response.OutputStream);
response.End();
}
public MemoryStream FillTemplateOpenXmlWord()
{
string filePath = @"c:\template.docx";
byte[] filebytes = File.ReadAllBytes(filePath);
using (MemoryStream stream = new MemoryStream(filebytes))
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
// do some changes
...
myDoc.MainDocumentPart.Document.Save();
}
return stream;
}
}
任何想法?
谢谢
我刚刚发现了同样的事情。当我得到答案时,我非常接近编辑我的问题并给出解决方案。 你说得对!我在使用条款中返回一个流。退货不会创建副本,而是创建参考。所以,在调用方法中,我得到了一个不在using子句中的流的引用。该流被丢弃,内容不再可用。 谢谢 – DotNetBeliever