2013-01-31 7 views
7

編集した後に返信したいdocxファイルがあります。私は、次のコードを持っている...MemoryStream docxファイルMVCを返すにはどうすればよいですか?

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が読めないコンテンツを発見した。あなたは、ソースを信頼する場合は[はい]をクリックします」 )。何か案は?

事前に感謝

EDIT

これは私のモデルで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; 
     } 
    } 
+2

"〜/ Documents/savedFile.docx"にあるファイルをダウンロードせずにWordで直接開くことはできますか?はいの場合、問題は不完全/破損ダウンロードです。もしそうでなければ、 'repo.ChangeFile'の中で何が起こっているのかを見せなければなりません。 –

+0

説明から、あなたが行った変更が正しく行われていないように思えます。 –

+2

'MemoryStream.ToArray()'メソッドは 'GetBuffer()'を使う必要がないことに注意してください。 – Lloyd

答えて

13

私は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"); 
6

ありませんMemoryStream.GetBuffer().ToArray()を使用MemoryStream.ToArray()

GetBuffer()は、メモリストリームの実際のデータではなく、メモリストリームの作成に使用される配列に関係しています。アンダーレイ配列は、実際にはサイズが異なる可能性があります。 MSDNの隠し

注バッファが未使用であるかもしれない割り当てられたバイトが含まれていること。 たとえば、文字列 "test"がMemoryStream オブジェクトに書き込まれた場合、GetBufferから返されるバッファの長さは、 ではなく256であり、252バイトは未使用です。バッファ内のデータのみを取得するには、ToArrayメソッドの を使用します。ただし、ToArrayは メモリにデータのコピーを作成します。

+0

あなたの答えは私のバグを解決しました:私はGetBufferを使用し、最後の行としてNULLの巨大な行を得ていました。 GetBufferをToArrayに置き換えて解決しました!ありがとう! – Alonzzo2

関連する問題