10

我有一个 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;
        }
    }
4

2 回答 2

15

我使用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");
于 2013-01-31T16:33:55.970 回答
10

不要使用MemoryStream.GetBuffer().ToArray()使用MemoryStream.ToArray()

原因GetBuffer()与用于创建内存流的数组有关,而不是与内存流中的实际数据有关。底层数组的大小实际上可能不同。

隐藏在 MSDN 上:

请注意,缓冲区包含可能未使用的已分配字节。例如,如果将字符串“test”写入 MemoryStream 对象,则从 GetBuffer 返回的缓冲区长度为 256,而不是 4,其中 252 个字节未使用。要仅获取缓冲区中的数据,请使用 ToArray 方法;但是,ToArray 会在内存中创建数据的副本。

于 2013-01-31T21:44:18.057 回答