Cannot download exe files through c#.net

asp.net, c#, download, exe

Solution

Can you please try this.

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.");
    }
}

I hope my edited comment will help to understand. But note: It is just a rough summary. You can do a lot more than this.

Problem

I have designed a website through which when i click a button a .EXE file should download from specific path from my computer. But its not downloading the exe file instead its downloading the aspx page of the website. I use the following code: ``` WebClient myWebClient = new WebClient(); // Concatenate the domain with the Web resource filename. myWebClient.DownloadFile("http://localhost:1181/Compile/compilers/sample2.exe", "sample2.exe"); ```

Original source