How to return a file MVC MemoryStream docx file?

I have a docx file that I would like to return after making changes. I have the following code ...

object useFile = Server.MapPath("~/Documents/File.docx"); object saveFile = Server.MapPath("~/Documents/savedFile.docx"); MemoryStream newDoc = repo.ChangeFile(useFile, saveFile); return File(newDoc.GetBuffer().ToArray(), "application/docx", Server.UrlEncode("NewFile.docx")); 

The file seems fine, but I get error messages (β€œthe file is damaged,” and the other indicates that β€œWord found unreadable content. If you trust the source, clickβ€œ Yes. ”) Any ideas?

Thanks in advance

EDIT

This is ChangeFile in my model ...

  public MemoryStream ChangeFile(object useFile, object saveFile) { byte[] byteArray = File.ReadAllBytes(useFile.ToString()); using (MemoryStream ms = new MemoryStream()) { ms.Write(byteArray, 0, (int)byteArray.Length); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) { string documentText; using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { documentText = reader.ReadToEnd(); } documentText = documentText.Replace("##date##", DateTime.Today.ToShortDateString()); using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) { writer.Write(documentText); } } File.WriteAllBytes(saveFile.ToString(), ms.ToArray()); return ms; } } 
+7
source share
2 answers

I am using FileStreamResult :

 var cd = new System.Net.Mime.ContentDisposition { FileName = fileName, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return new FileStreamResult(documentStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 
+13
source

Do not use MemoryStream.GetBuffer().ToArray() use MemoryStream.ToArray() .

The reason that GetBuffer() refers to the array used to create the memory stream, and not to the actual data in the memory stream. The lining matrix may actually vary in size.

Hidden in MSDN:

Note that the buffer contains allocated bytes, which may be unused. For example, if the string "test" is written to a MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes not used. To get only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

+6
source

All Articles