http Downloading Files and Browser Issues

While working on a project, I needed to download a document from the database and stream it to the client.  Our standard browser was IE 7+ and the standard code implementation documented throughout many forums the following with the first line simply obtaining the file via a service:
 byte[] fileContents = csc.GetFileContent(this.CurrentContentId);
Response.ClearContent();
Response.ContentType = this.ContentType;
Response.AddHeader("content-disposition", string.Format("attachment;
       filename={0}", this.ContentFileName));
Response.AddHeader("content-length", fileContents.Length.ToString());
Response.BinaryWrite(fileContents);
Response.Flush();
Response.End(); 

The "Response.End()" at the end will cause a ThreadAbort exception within IE and other browsers.  The solution to this was to wrap this code inside a try-catch block and absorb the ThreadAbortException as follows:
try 
{
   //code above here
}
catch(ThreadAbortException taEx)
{
   //absort exception thrown by Response.End
}
catch(Exception ex)
{
   //error handling
}

The problem with this is that some browsers like Apples Safari will throw an Exception regardless.  The solution is to change the code to the following:
byte[] fileContents = csc.GetFileContent(this.CurrentContentId);
Response.ClearContent();
Response.ContentType = this.ContentType;
Response.AddHeader("content-disposition", string.Format("attachment;
       filename={0}", this.ContentFileName));
Response.AddHeader("content-length", fileContents.Length.ToString());
Response.BinaryWrite(fileContents);
Response.Flush();
Response.Close(); 
HttpContext.Current.ApplicationInstance.CompleteRequest();

The above will get rid of the ThreadAbortException exception.

 

Comments

Popular posts from this blog

Debug VBScript / VBS files in Visual Studio 2010

A good use of Common Table Expressions

Setting Up Visual Studio Environment for Selenium