How do I return a MemoryStream docx file MVC?

MrM picture MrM · Jan 31, 2013 · Viewed 21.4k times · Source

I have a docx file that I would like to return after I make edits. 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 am getting error messages ("the file being corrupt" and another stating "Word found unreadable content. If you trust the source click Yes"). Any ideas?

Thanks in advance

EDIT

This is the 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;
        }
    }

Answer

Parker picture Parker · Jan 31, 2013

I use a 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");