2017-09-25 54 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並返回文件。

編輯: 下面的代碼是我的新的當前的代碼和我期待的方向走去,但是當我使用一個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

這仍然會將我重定向到包含文件數據的新頁面,但不會強制用戶下載文件。 –

相關問題