Click here to Skip to main content
15,881,204 members
Articles / Web Development / ASP.NET

Download Files in ASP.NET

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
30 Sep 2013CPOL1 min read 56.5K   13   2
How to download different types of files in asp.net

Sometimes client applications need to retrieve different types of files (.doc, .xls, .zip…etc.) from web application to do some of their internal works or even just for the users. So, if we could make such web application which provides the facility to the client applications to download different files from the server, we don’t need to change or modify the code of the web application each time we upload the different types of file to the server.

This can be easily achieved by using an HTTP Handler for download operation. We can use normal ASP.NET web page for this purposes, but the reason behind to choose an HTTP Handler is only for performance issues. Firstly, we get benefit of scalability as we don’t need to show any output value to the page. Secondly, an HTTP handler doesn’t go through the full page events which ultimately improve performance.

The handler code has given below which is self-descriptive and requires no more description,

C#
public class Download : IHttpHandler
{
 public bool IsReusable
 {
    get
    {
     return false;
    }
 }

 public void ProcessRequest(HttpContext context)
 {
    var request = context.Request;
    Stream stream = null;
    var buffer = new byte[2048];
    var fileName = request["FileName"];

    if (string.IsNullOrEmpty(fileName))
       throw new Exception("File name is Empty");

    var fullFileName = Path.Combine(string.Format("{0}", 
        request.PhysicalApplicationPath), "DownloadFiles",fileName);
    try
    {
       stream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
       var dataToRead = stream.Length;
       while (dataToRead > 0)
       {
          if (context.Response.IsClientConnected)
          {
             var length = stream.Read(buffer, 0, 2048);
             context.Response.OutputStream.Write(buffer, 0, length);
             context.Response.Flush();
             buffer = new byte[2048];
             dataToRead = dataToRead - length;
          }
          else
          {
             dataToRead = -1;
          }
       }
    }
    catch (Exception ex)
    {
       context.Response.Write(ex);
    }
    finally
    {
       if (stream != null)
       {
          stream.Close();
       }
    }
  }
}

The client applications need to send a request to the download handler appending the Filename variable in the QueryString. This is also a laid-back substance. I am giving a sample code for that,

C#
var fileName = string.Format("{0}","Install.zip");
var queryString = string.Format("{0}{1}{2}", "FileName", "=", fileName);
var downloadUrl = URL of Download.ashx;
var url = string.Format("{0}{1}{2}", downloadUrl,"?", queryString);
var downBuffer = new byte[2048];

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.KeepAlive = false;
webRequest.UnsafeAuthenticatedConnectionSharing = true;
webRequest.Credentials = CredentialCache.DefaultCredentials;
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var streamResponse = webResponse.GetResponseStream();
var fileStream = new FileStream(string.Format("{0}{1}", 
    "D:\\", fileName), FileMode.Create, FileAccess.Write);

if (streamResponse != null)
{
     int bytesRead;
     while ((bytesRead = streamResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
     {
         fileStream.Write(downBuffer, 0, bytesRead);
     }
}

fileStream.Close();

Here, I host the web application to the local IIS and the URL for download handler is ‘…/Download.ashx’. WebRequest is for making a request to a URI and HttpWebRequest offers an HTTP specific operation of WebRequest where HttpWebResponse delivers a response from a URI.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer RightKnack Limited
Bangladesh Bangladesh
A big fan of getting down the latest cutting-edge technologies to the ground to innovate exceptionally amazing ideas.

My Blog: http://rashimuddin.wordpress.com/

My Email: rashimiiuc at yahoo dot com

Comments and Discussions

 
Questionmessage Pin
Siva Hyderabad26-Feb-14 19:04
Siva Hyderabad26-Feb-14 19:04 
AnswerRe: message Pin
Md. Rashim Uddin26-Feb-14 20:17
Md. Rashim Uddin26-Feb-14 20:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.