4

Here is my code I tried following way to put functionality for download a file but it doesn't work properly. It doesn't show save file dialog.

 protected virtual FileResult Download(string FileName, string FilePath)
 {

        Response.AppendHeader("Content-Length", FileName.Length.ToString());
        return File(FilePath, "application/exe", FileName);
 }

And tried this way also:

protected virtual ActionResult Download(string FileName, string FilePath)
{
    Response.Clear();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.AppendHeader("Content-Length", FileName.Length.ToString());
    Response.ContentType = "application//x-unknown";
    Response.WriteFile(FilePath.Replace("\\", "/"));
     Response.Flush();
    Response.End(); 
}

But both are not working. What I missing?

Mehul Patel
  • 1,084
  • 2
  • 12
  • 28
  • I hope you are Aware about the security Problems your filepath and filename variables come along with... – TGlatzer Aug 26 '13 at 13:00
  • Filename length != Content length. Also, its likely browsers are blocking the executable download. I know my IE does.. and Chrome throws up a "are you absolutely sure?" Prompt. – Simon Whitehead Aug 26 '13 at 13:05
  • See this similar question: http://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult – Roy Dictus Aug 26 '13 at 13:10
  • I tried with .doc file also and from same location it works well for exe file in asp.net. – Mehul Patel Aug 27 '13 at 05:24
  • This may be because of file compression (default I believe). Text works because the browser knows how to uncompress the files. Binary files (PDF, DOCX, etc.) compressed still look like binary files. – Mark Lopez Jan 15 '14 at 21:02

2 Answers2

4

I don't know major difference but following code is working fine for me for any file..May be because of ContentType as per @Garath suggest.

var fileInfo = new System.IO.FileInfo(oFullPath);
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", yourfilename));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.WriteFile(oFullPath);
            Response.End();
Mehul Patel
  • 1,084
  • 2
  • 12
  • 28
2

The correct mimitype for exe file is application/octet-stream not application/exe or application//x-unknown - check MSDN You could look here for more definitions: Get MIME type from filename extension

Community
  • 1
  • 1
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • I get all things right but problem is that only txt files are download perfactly but doc files or pdf files are download but in corrupted format. – Mehul Patel Aug 28 '13 at 07:24