tags:

views:

31

answers:

2

I want to allow my user to click on a button that says "download" and then will build a dynamic csv file on the fly and will prompt the user to download. I know how to build the file using a HTTPHandler, but not quite sure the mechanism for delivering the content via download.

A: 

Just emit a Content-Disposition HTTP header in your HTTP Handler code. Most browsers will interpret that as a download request. Replace yourfile.csv by the filename you want the user to see.

context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=yourfile.csv");
Julien Lebosquain
+3  A: 

I usually create a Generic Handler (.ashx) and do something like this:

public void ProcessRequest(HttpContext context)
{
   StringBuilder myCsv = new StringBuilder();
   foreach(myRow r in myRows) {
     myCsv.AppendFormat("\"{0}\",{1}", r.MyCol1, r.MyCol2);
   }

   context.Response.ContentType = "application/csv";
   context.Response.AddHeader("content-disposition", "attachment; filename=myfile.csv");
   context.Response.Write(myCsv.ToString());
}

Now if the CSV you're building is REALLY big, you might want to write out each row as you create it, rather than stuffing it into a StringBuilder.

Coding Gorilla