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; } }
MrM
source share