Archive December 2011

How to force download a file using ASP.NET

There are many cases where we need to let file downloads being processed by an aspx file. Here in this code this code will force a file to be downloaded through an aspx file. let assume your file path  is in “string path” variable. Add this code in your aspx file cs file.

 


string path = "the path to your file";
string fileName = "Add your file name";
string contentType= "Add your file content type. ex: for text file it is 'text/plain'";
string contentLength = "add string presentation of your file size in bytes";

response.Clear();
response.ClearHeaders();
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
response.AddHeader("Content-Length", contentLength);
response.ContentType = contentType;
FileStream f = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = f.Read(buffer, 0, buffer.Length)) > 0)
{
    response.OutputStream.Write(buffer, 0, len);
}
response.OutputStream.Flush();
response.OutputStream.Close();
response.Flush();
response.Close();
response.End();
No Comments