I was working with code that allowed the user to save an Excel file by clicking on a link on a web page. The user was then prompted to open, save, or cancel the file. This little code snippet accomplishes this, the MyStream object being a MemoryStream object:
Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "ScottsCoolFile.xls"); Response.Clear(); Response.BinaryWrite(MyStream ().GetBuffer()); Response.End();
The problem with this code is that is throws a ThreadAbortException on the call to Response.End(). I don’t know about you, but this is not what I want happening. Exceptions = bad.
A little research led me to the HttpApplication.CompleteRequest method. So I replaced the last line of the code above, and I then had:
Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "ScottsCoolFile.xls"); Response.Clear(); Response.BinaryWrite(WriteToStream().GetBuffer()); HttpContext.Current.ApplicationInstance.CompleteRequest();
Voila, same functionality, but no exception.
#1 by Tim Golisch on January 30, 2012 - 5:44 pm
Love it. +1 (if I could)
#2 by Anders G. Nordby on August 23, 2012 - 12:51 pm
Thank you, this really saved my day! You’ve no idea how long I searched for a solution before stumbling onto this blog post!