Forcing a download in ASP.NET

I recently had a situation where I had to generate a CSV file as a result of a set of queries and force that file to be downloaded to the browser. The solution is remarkable simple.

Assuming a button on the page:

protected void Button1_Click(object sender, EventArgs e) {
string s = GetData(); // some function to generate te download’s content
Response.Clear();
Response.AddHeader(“content-disposition”, “attachment; filename=orders.csv”);
Response.Write(s);
Response.Flush();
//required so that the page’s rendered content isn’t appended to the end of the download. */
Response.Close();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s