ASP.NET/C# Prompt a Save Dialog Box to Download a File

May 15th, 2009

To save you all (as well as my future self) the trouble of searching all over the place just to find terrible answers on almost every form post out there. Here is a small ASP.NET/C# code snippet that will prompt the user with the save/open dialog box to download a file.

String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();

For more content types check our http://en.wikipedia.org/wiki/MIME_type#List_of_common_media_types

4 Responses to "ASP.NET/C# Prompt a Save Dialog Box to Download a File"

  1. Nabeel says:

    Thank you soooo much! This worked for me.

  2. Ali says:

    man this works for one imagebutton but didnot work for the second imagebutton on the same page.Will you please give a good reason for this

  3. Jonathan Berber says:

    This works perfectly and solves a lot of problems – thank you.

  4. Manoj says:

    I am getting an exception in the last line of code Unauthorized exception was unhand led by users code

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>