Allowing the user to load from my site through Response.WriteFile ()

I am trying to programmatically download a file by clicking a link on my site (this is 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 the buttonclick event handler. Well, I could do something with the file / file code to make it tidier, but when I click the button, the page refreshes. On the local host, this code works fine and allows me to upload the file in order. What am I doing wrong?

thanks

0
source share
3 answers

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(); } 
0
source share

Instead of having a button click event handler, you might have a download.aspx page that you could link to.

This page can then contain 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.

+1
source share

Oh, you shouldn't do this in the button click event handler. I suggest moving all of this to an HTTP handler ( .ashx ) and using Response.Redirect or any other redirect method to bring the user to this page. My answer to this question contains a sample .

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

0
source share

All Articles