How to download a file in ASP.Net

Here is perhaps the simplest, shortest way to download a file in an ASP.Net application:
  1. Response.ContentType = "application/pdf";  
  2. Response.AppendHeader("Content-Disposition""attachment; filename=MyFile.pdf");  
  3. Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf"));  
  4. Response.End();  
The first step is to set the content type.   In the example above, we're downloading a .pdf file.  Here are some of the most common content types:
 
.htm, .html     Response.ContentType = "text/HTML";
.txt    Response.ContentType = "text/plain";
.doc, .rtf, .docx    Response.ContentType = "Application/msword";
.xls, .xlsx    Response.ContentType = "Application/x-msexcel";
.jpg, .jpeg    Response.ContentType = "image/jpeg";
.gif    Response.ContentType =  "image/GIF";
.pdf    Response.ContentType = "application/pdf";
 
Response.TransmitFile retrieves a file and writes it to the Response.  By calling TransmitFile, you are ensuring that the Open / Save dialong will open on the browser, as opposed to simply opening the file in the browser window.
 
filedownload1.gif 
 
In some cases, we can't call TransmitFile because we can't map a path to the file.  Instead, we'll get the file as a Stream and write it to the Response object: 
  1. Response.ContentType = "application/pdf";  
  2. Response.AppendHeader("Content-Disposition""attachment; filename=MyFile.pdf");  
  3.   
  4. // Write the file to the Response  
  5. const int bufferLength = 10000;  
  6. byte[] buffer = new Byte[bufferLength];  
  7. int length = 0;  
  8. Stream download = null;  
  9. try  
  10. {  
  11.     download = new FileStream(Server.MapPath("~/Files/Lincoln.txt"),  
  12.                                                    FileMode.Open,  
  13.                                                    FileAccess.Read);  
  14.     do  
  15.     {  
  16.         if (Response.IsClientConnected)  
  17.         {  
  18.             length = download.Read(buffer, 0, bufferLength);  
  19.             Response.OutputStream.Write(buffer, 0, length);  
  20.             buffer = new Byte[bufferLength];  
  21.         }  
  22.         else  
  23.         {  
  24.             length = -1;  
  25.         }  
  26.     }  
  27.     while (length > 0);  
  28.     Response.Flush();  
  29.     Response.End();  
  30. }  
  31. finally  
  32. {  
  33.     if (download != null)  
  34.         download.Close();  
  35. }  
As before, the Open / Save dialog should open in the browser.
 
The project download includes working examples of both of these techniques.