Skip to main content

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.


Comments

Popular posts from this blog

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET. Previous Post  I was Explained about the   jQuery - Allow Alphanumeric (Alphabets & Numbers) Characters in Textbox using JavaScript  ,  Fileupload show selected file in label when file selected  ,  Check for file size with JavaScript before uploading  . May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control  which supports Multiple File Upload, Progress Bar and Drag And Drop functionality. These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature. To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager  and AjaxFileUpload on the page. HTML SOURCE < asp:ToolkitScriptManager I...

How to send mail asynchronously in asp.net with MailMessage

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like offers , Discounts , Greetings . You don’t have to wait for response from mail server and you can do other task . By using     SmtpClient . SendAsync Method (MailMessage, Object)    you need to do  System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to Wire up a SendCompleted event Create the SendCompleted event Call SmtpClient.SendAsync smtpClient.send() will initiate the sending on the main/ui  thread and would block.  smtpClient.SendAsync() will pick a thread from the .NET Thread Pool and execute the method on that thread. So your main UI will not hang or block . Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail success...

ASP.NET Routing

ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. The ASP.NET MVC framework and ASP.NET Dynamic Data extend routing to provide features that are used only in MVC applications and in Dynamic Data applications. For more information about MVC, see ASP.NET MVC 3 . For more information about Dynamic Data, see ASP.NET Dynamic Data Content Map . In an ASP.NET application that does not use routing, an incoming request for a URL typically maps to a physical file that handles the request, such as an .aspx file. For example, a request for http://server/application/Products.aspx?id=4 maps to a file that is named Products.aspx that contains code and markup for rendering a response to the browser. The Web page uses the query string value of id=4 to determine what type of c...