2012-01-31 62 views
0

下面是下載文件的代碼。我的網址有效(可以下載),但是我的網址2無效(無法下載)。我爲url2做了什麼錯誤?我的相對路徑出現任何問題?c#下載按鈕url error

protected void Button1_Click(object sender, EventArgs e) 
{ 
    string url [email protected]"C:\Users\Roy\Desktop\backup fyp\10-18-2011\WebSite5\123.txt"; 
    string url2 = @"~\123.txt"; 
    FileInfo finfo = new FileInfo(url); 

    if (finfo.Exists) 
    { 
     Response.Clear(); 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + finfo.Name); 
     Response.AddHeader("Content-Length", finfo.Length.ToString()); 
     Response.ContentType = "application/octet-stream"; 
     Response.Flush(); 
     Response.WriteFile(finfo.FullName); 
    } 
    else 
    { 
     Response.Write("error"); 
    } 
} 
+3

究竟是什麼不起作用?你有404錯誤嗎?你得到錯誤的文件?有什麼事情發生嗎? – Mixxiphoid 2012-01-31 07:09:59

+0

爲第一個網址,我的文件能夠下載,這是123.txt,爲url2,我的文件無法找到=( – 2012-01-31 07:13:39

回答

2

~\123.txt是一個虛擬路徑。你需要像這樣使用它:

string url2 = HttpContext.Current.Server.MapPath(@"~\123.txt"); 
+0

,嗨,它的工作,謝謝=) – 2012-01-31 07:18:44