2017-09-25 7 views
0

ジャーナルエントリをテキストファイルにエクスポートできるようにしたいと考えています。すべてのデータを含むファイルを作成することはできますが、ユーザーがコンピュータ上でファイルをダウンロードして保存できるように、特定の場所にファイルを厳密に保存することができます。 StreamWriterでファイルを作成した後、ファイルのダウンロードを強制する方法。私は現在次のコードを持っています:作成したファイルをユーザーのコンピュータに強制的にダウンロードする方法C#

string fileName = "Journal.txt"; 

     using (StreamWriter journalExport = new StreamWriter(fileName)) 
     { 
      foreach (JournalEntryView entry in journalEnteries) 
      { 
       //write each journal entery to file/document 
       journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")"); 
       journalExport.WriteLine(entry.text); 
       journalExport.WriteLine(""); 
       journalExport.WriteLine(""); 
      } 
     } 

これをActionResultに入れてファイルを返します。

EDIT:は、次のコードは、私の新しい現在のコードと私が行くことを探しています方向で が、私は、このメソッドを呼び出すActionLinkのを使用する場合、私はちょうどダウンロードするのではなく、新しいページにリダイレクトされますファイル。

string fileName = "Journal.txt"; 
     string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName; 

     using (StreamWriter journalExport = new StreamWriter(filepath)) 
     { 
      foreach (JournalEntryView entry in journalEnteries) 
      { 
       //write each journal entery to file/document 
       journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")"); 
       journalExport.WriteLine(entry.text); 
       journalExport.WriteLine(""); 
       journalExport.WriteLine(""); 
      } 

     } 

     byte[] fileData = System.IO.File.ReadAllBytes(filepath); 
     string contentType = MimeMapping.GetMimeMapping(filepath); 

     var cd = new System.Net.Mime.ContentDisposition 
     { 
      FileName = fileName, 
      Inline = true, 
     }; 

     Response.AppendHeader("Content-Disposition", cd.ToString()); 

     return File(fileData, contentType); 
+1

あなたは 'FileContentResult'と'ファイル() 'メソッドを見ていましたか? – SLaks

+0

私は持っていますが、私のニーズを達成するためにそれらを使う方法がわかりません –

答えて

0

これは、あなたが探しているものかもしれません:

public ActionResult GetFile() 
{ 
    ...processing stuff... 
    return File("/files/file.pdf", "application/pdf"); 
    //or 
    return File("/files/file.pdf", "application/force-download", "donwloadname.pdf"); 
} 
+0

"files/file.pdf"と "downloadname.pdf"はどこから来たのですか? –

+0

'File'メソッドが許すパラメータを見ることができますが、私の例では" /files/files.pdf "はpdfへのパスであり、" downloadname.pdf "はユーザにpdfを渡したいときの名前ですファイルをダウンロードします。あなたのアーキテクチャがわからないので、アプリケーションに値をカスタマイズする必要があります。 –

+0

これは、myをファイルデータを含む新しいページにリダイレクトしますが、ユーザーにファイルのダウンロードを強制しません。 –

関連する問題