Serving up a file for download

I’m back again! So recently I had to make an application that zips up and serves up files to the browser and I thought that I should share my code to help anyone out there trying to do the same.


// Sever up to browser
if (System.IO.File.Exists(reportPath))
{
//Get file size
string fileLength = new System.IO.FileInfo(reportPath).Length.ToString();

//Serve up file to the browser
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", fileLength);
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", reportPath));
Response.WriteFile(reportPath);
Response.Flush();
Response.Close();// I dont use Response.End()
}

Please note that I use Response.Close() instead of Response.End(). Using Response.End() result in an uncatchable yet non-critical exception being thrown.

See this Link for more information: http://stackoverflow.com/questions/1087777/is-response-end-considered-harmful

Luke

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s