我有一个 docx 文件,我想在编辑后返回。我有以下代码...
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"));
该文件看起来不错,但我收到错误消息(“文件已损坏”和另一个说明“Word 发现不可读的内容。如果您信任来源,请单击是”)。有任何想法吗?
提前致谢
编辑
这是我模型中的 ChangeFile ......
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;
}
}