0

I am trying to programatically download a file through clicking a link, on my site (it's a .doc file sitting on my web server). This is my code:

string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";

if (System.IO.File.Exists(FileName))
{

    FileInfo fileInfo = new FileInfo(File);
    long Length = fileInfo.Length;


    Response.ContentType = "Application/msword";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
    Response.AddHeader("Content-Length", Length.ToString());
    Response.WriteFile(fileInfo.FullName);
}

This is in a buttonclick event handler. Ok I could do something about the file path/file name code to make it neater, but when clicking the button, the page refreshes. On localhost, this code works fine and allows me to download the file ok. What am I doing wrong?

Thanks

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
GurdeepS
  • 65,107
  • 109
  • 251
  • 387
  • Stupid question: does "filename.doc" exist on the server in the same location (relative to the Application Root)? – Stobor Jun 21 '09 at 22:52

3 Answers3

1

Rather than having a button click event handler you could have a download.aspx page that you could link to instead.

This page could then have your code in the page load event. Also add Response.Clear(); before your Response.ContentType = "Application/msword"; line and also add Response.End(); after your Response.WriteFile(fileInfo.FullName); line.

solrevdev
  • 8,863
  • 11
  • 41
  • 49
0

Oh, you shouldn't do it in button click event handler. I suggest moving the whole thing to an HTTP Handler (.ashx) and use Response.Redirect or any other redirection method to take the user to that page. My answer to this question provides a sample.

If you still want to do it in the event handler. Make sure you do a Response.End call after writing out the file.

Community
  • 1
  • 1
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
0

Try a slightly modified version:

string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";

if (System.IO.File.Exists(FileName))
{

    FileInfo fileInfo = new FileInfo(File);


    Response.Clear();
    Response.ContentType = "Application/msword";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
    Response.WriteFile(fileInfo.FullName);
    Response.End();
}
Hans Malherbe
  • 2,988
  • 24
  • 19