Click here to Skip to main content
Click here to Skip to main content

Download Files in ASP.NET

By , 30 Sep 2013
Rate this:
Please Sign up or sign in to vote.

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,

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,

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)

About the Author

Md. Rashim uddin
Software Developer (Senior) KAZ Software Limited.
Bangladesh Bangladesh
I am nothing more than a simple man with the high vision of evolving multifaceted software systems by using my technical and interpersonal skills which will complement my professional growth. I feel enjoyment to take challenges to resolve those technical problems which are yet to be solved.
 
My Blog: http://rashimuddin.wordpress.com/
 
My Email: rashimiiuc at yahoo dot com
Follow on   Twitter

Comments and Discussions

 
Questionmessage PinmemberSambasivaRaoG26-Feb-14 19:04 
AnswerRe: message PinmemberMd. Rashim uddin26-Feb-14 20:17 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 30 Sep 2013
Article Copyright 2013 by Md. Rashim uddin
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid