2012-10-19 294 views
-1

我製作了一個文本文件並保存到項目文件夾中的一個位置。 如何將它們重定向到包含該文本文件的url,以便它們可以下載該文本文件。如何從網址下載.txt文件?

CreateCSVFile將csv文件創建爲基於數據表的文件路徑。

呼叫:

string pth = ("C:\\Work\\PG\\AI Handheld Website\\AI Handheld Website\\Reports\\Files\\report.txt"); 
CreateCSVFile(data, pth); 

而且功能:

public void CreateCSVFile(DataTable dt, string strFilePath) 
{ 

    StreamWriter sw = new StreamWriter(strFilePath, false); 
    int iColCount = dt.Columns.Count; 

    for (int i = 0; i < iColCount; i++) 
    { 
     sw.Write(dt.Columns[i]); 

     if (i < iColCount - 1) 
     { 
      sw.Write(","); 
     } 
    } 

    sw.Write(sw.NewLine); 
    // Now write all the rows. 
    foreach (DataRow dr in dt.Rows) 
    { 
     for (int i = 0; i < iColCount; i++) 
     { 
      if (!Convert.IsDBNull(dr[i])) 
      { 
       sw.Write(dr[i].ToString()); 
      } 

      if (i < iColCount - 1) 
      { 
       sw.Write(","); 
      } 
     } 
     sw.Write(sw.NewLine); 
    } 
    sw.Close(); 
    Response.WriteFile(strFilePath); 
    FileInfo fileInfo = new FileInfo(strFilePath); 

    if (fileInfo.Exists) 
    { 
     //Response.Clear(); 
     //Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); 
     //Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 
     //Response.ContentType = "application/octet-stream"; 
     //Response.Flush(); 
     //Response.TransmitFile(fileInfo.FullName); 

    } 
} 

回答

1

之後sw.Close();只是Response.Redirect()他們到的文本文件的URL。您必須獲取URL,而不是物理硬盤上的路徑。根據你的代碼,你可以做到以下幾點:

Uri appRootUri = new Uri(HttpContext.Current.Request.ApplicationPath); 
Uri fileUri = new Uri(Path.GetFullPath(strFilePath)); 

Uri relativeUri = fileUri.MakeRelativeUri(appRootUri); 

Response.Redirect("~/" + relativeUri.ToString()); 

正如意見建議的阿奎那,你真的應該去,雖然其他的方式。你應該知道你要存儲文件的相對路徑,在這種情況下,你可以這樣做:

// If you want to store it at http://yourapplication/files/file.txt 
string relativeFilePath = "/files/file.txt"; 

CreateCSVFile(dt, Server.MapPath(relativeFilePath)); 
Response.Redirect("~" + relativeFilePath); 
+0

個人而言,我認爲這是錯誤的方法。他當然知道他想要放置文件的URL?例如,〜/ Reports/Files/Report.txt。那麼,他應該從虛擬路徑獲得物理路徑,而不是相反。例如'string physicalPath = Server.MapPath(「〜/ Reports/Files/report.txt」)。'我的兩分錢。 – aquinas

+0

是的,我同意,我想我只是基於他提供的代碼框架來回答。我會用更好的方式更新我的答案。 –

1

的Response.Redirect( 「〜/報告/文件/ REPORT.TXT」);