ASP.Net: Downloading Files

by matt 30. January 2009 16:52

I was asked today how to go about downloading a file as a response to a server request.  I think last time I had to do that was in that days of ASP.Classic.

Anyhow, incase you are interested, the following code will allow you to download content through the browser and should bring up the browser save dialogue.

// Load a lovely file (yep - I'm not too concerned about permissions here) and
// read it into a buffer
FileStream fs = new FileStream(@"C:\TestXMLFile.xml", FileMode.Open);
long fileSize = fs.Length;
byte[] fileBuffer = new byte[Convert.ToInt32(fileSize)];
fs.Read(fileBuffer, 0, (int)fileSize);
fs.Close();
 
// Change the response headers
Response.ContentType = "text/xml";
Response.AddHeader("content-disposition", "attachment; filename=myXmlFile.xml");
 
// Write out the buffer
Response.BinaryWrite(fileBuffer);

The key part here is that we're changing the content type and the disposition header telling the client browser what it's expecting and what to do.  You can find more information on the Microsoft support site knowledge base: HOWTO: Raise a "File Download" Dialog Box for a Known MIME Type.

Tags:

.Net Framework | ASP.NET

Comments

2/11/2009 1:46:03 PM #

Gee thanks Matt. I had a similar requirement at ratemycheese.com (Under construction). You've turned my problem into a Response.Right!

Steve Cheese |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar