无法通过c#.net下载exe文件

时间:2014-02-17 07:25:34

标签: c# asp.net download exe

我设计了一个网站,当我点击一个按钮时,.EXE文件应该从我的电脑的特定路径下载。

但它不下载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");

1 个答案:

答案 0 :(得分: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.");
    }
}

我希望我编辑的评论有助于理解。但请注意:这只是一个粗略的总结。你可以做更多的事情。