I've spent the last couple days attempting to address this issue. I've performed exhaustive Google searches, tried many solutions, with no luck.
In essence, I'm trying to export data to a CSV and download it. The code works, but throws an exception. My particular usage requires for multiple downloads (like the example below) to occur back-to-back, but the exception prevents this from happening.
string attachment = string.Format("attachment; filename={0}_OutPut.csv", companyName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName("Column1,Column2,Column3");
StringBuilder stringBuilder = new StringBuilder();
foreach (Item i in list.Items)
{
AddData(i.TaxCodeValue.ToString(), stringBuilder);
AddData(i.Description.ToString(), stringBuilder);
AddData(i.Description.ToString(), stringBuilder);
stringBuilder.Length = 0; //Reset Stringbuilder value
HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}
HttpContext.Current.Response.End(); <---This is the problem
I've read:
http://support.microsoft.com/kb/312629
Alternative to Response.End()?
Thread was being aborted when exporting to excel?
I understand Response.End() is throwing an exception because it is aborting the thread (generally not advised). However, for my scenario, I don't see any alternative.
A few of the things I've tried:
HttpContext.Current.ApplicationInstance.CompleteRequest();
as an alternative to Response.End(). It results in my CSV being filled with garbage, and not the actual data I'm writing.HttpContext.Current.Response.Redirect("Page.aspx", false);
just refreshes the page, and the written data is not downloaded.- Catching the exception within a catch block. It always manages to escape and ripple up.
Any ideas?
Thank you in advance.