2014-02-17 69 views
5

我設計了一個網站,通過它我點擊一個按鈕時.EXE文件應該從我的電腦的特定路徑下載。無法通過c#下載exe文件.net

但它並沒有下載exe文件,而是下載了網站的aspx頁面。

我使用下面的代碼:

WebClient myWebClient = new WebClient(); 
// Concatenate the domain with the Web resource filename. 
myWebClient.DownloadFile("http://localhost:1181/Compile/compilers/sample2.exe", "sample2.exe"); 
+0

該頁面的內容是什麼?確保它不是403錯誤或什麼 – Sarrus

+0

@Sarrus沒有403錯誤。頁面的內容是文本框和按鈕。\ –

回答

5

能否請您試試這個。

string filename = "yourfilename"; 
if (filename != "") 
{ 
    string path = Server.MapPath(filename); 
    System.IO.FileInfo file = new System.IO.FileInfo(path); 
    if (file.Exists) 
    { 
     Response.Clear(); 
     //Content-Disposition will tell the browser how to treat the file.(e.g. in case of jpg file, Either to display the file in browser or download it) 
     //Here the attachement is important. which is telling the browser to output as an attachment and the name that is to be displayed on the download dialog 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
     //Telling length of the content.. 
     Response.AddHeader("Content-Length", file.Length.ToString()); 

     //Type of the file, whether it is exe, pdf, jpeg etc etc 
     Response.ContentType = "application/octet-stream"; 

     //Writing the content of the file in response to send back to client.. 
     Response.WriteFile(file.FullName); 
     Response.End(); 
    } 
    else 
    { 
     Response.Write("This file does not exist."); 
    } 
} 

我希望我編輯的評論能幫助理解。但請注意:這只是一個粗略的總結。你可以做的比這更多。

+0

其工作正常..謝謝你Usman ..但實際上我無法理解你的代碼,你可以解釋一下。 –

+0

你想了解什麼?我的意思是哪條線? –

+0

Response.AddHeader(「Content-Disposition」,「attachment; filename =」+ file.Name); Response.AddHeader(「Content-Length」,file.Length.ToString()); Response.ContentType =「application/octet-stream」; Response.WriteFile(file.FullName); –