Sending dynamically generated files to the browser in ASP.NET
Introduction
Let’s suppose that you’ve got some data in your ASP.NET page, and you want to send it to your users as a file that they can download to their desktop. It doesn’t really matter what type of data, it could be a Microsoft Word document, a JPEG image or maybe just some plain boring text. It might’ve been loaded from a file somewhere, or generated dynamically inside the page.
In this example we’ll use some XML because it’s nice and simple. Maybe it’s your company’s monthly sales figures and users need to download the data to generate reports.
Setting the HTTP headers
You’ve got your data, in this case encapsulated in an XmlDocument object, and you’re ready to send it to the browser. The first step is to tell the browser what kind of data you’re going to be sending by setting the “content-type” HTTP header to “text/xml”. Usually this is set to “text/html” for regular HTML content, but you can use whichever MIME type matches your data.
Next, tell the browser not to display the data, but instead prompt the user with a file download dialog. You also need to give your file a name, otherwise the filename of your .aspx page will be used by default. Both these things are achieved by adding another HTTP response header, “content-disposition”.
Finally, send your data to browser. Here’s some example code to illustrate:
XmlDocument xmlDoc = new XmlDocument();
// (build your XML document here)
Response.AppendHeader("content-type", "text/xml");
Response.AppendHeader("content-disposition", "attachment;filename=data.xml");
Response.Write(xmlDoc.OuterXml);
Response.End();
Note the use of AppendHeader to set your page response’s HTTP header information.
You should be presented with a file download dialog to save your XML file:

Summary
This technique can be used for all sorts of things, among the most useful are probably serving downloadable reports to your users, and providing protected access to files outside the webroot.