How to download a file in ASP.Net


Here is perhaps the simplest, shortest way to download a file in an ASP.Net application:

Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf"));
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: 

Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");

// Write the file to the Response
const int bufferLength = 10000;
byte[] buffer = new Byte[bufferLength];
int length = 0;
Stream download = null;
try
{
    download = new FileStream(Server.MapPath("~/Files/Lincoln.txt"),
                                                   FileMode.Open,
                                                   FileAccess.Read);
    do
    {
        if (Response.IsClientConnected)
        {
            length = download.Read(buffer, 0, bufferLength);
            Response.OutputStream.Write(buffer, 0, length);
            buffer = new Byte[bufferLength];
        }
        else
        {
            length = -1;
        }
    }
    while (length > 0);
    Response.Flush();
    Response.End();
}
finally
{
    if (download != null)
        download.Close();
}

As before, the Open / Save dialog should open in the browser.

The project download includes working examples of both of these techniques.

Up Next
    Ebook Download
    View all
    Learn
    View all