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.