Overview
This article explains how to create download file handler in cs.net. On internet, sometime we click on some for file download and one dialog box pops up saying open or download file. How to create that link dynamically? Let’s see it in action.
Screenshot
Here is the screenshot of download file dialog box.

Steps:
1. Add new ashx file
First open your webapplication. Go to file > new file then select generic handler from list and click add.
Extension for the file will be ashx. i.e. give name “downloadfile.ashx”
2. Add Code to ashx
Add following code to ashx file OR you can download complete ashx file attached with this article.
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var r = context.Response;
r.ContentType = "text/plain";
try
{
//Add some authentication check code here..
if (HttpContext.Current.Request.QueryString["n"] != null)
{
var file = HttpContext.Current.Request.QueryString["n"].ToString();
r.AddHeader("Content-Disposition", "attachment; filename=" + file);
r.WriteFile(Path.Combine(settings.UserViewRunDir, file));
//*** setting is my static class with dir name assigned to UserViewRunDir, that is r.(“path to the file”)
}
}
catch(Exception ex)
{
context.Response.Redirect("Error.aspx?err=301");r.Flush();
//r.ContentType = "text/HTML";
//context.Response.Write("Error downloading file..<br/>Detail:<br/>" + ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
3. What to change?
In Source page, I have asp:HyperLink and I’m assigning dynamic link to it by following code
HLSave.NavigateUrl = "downloadfile.ashx?n=" + foldername + "/" + sfile[0];
Foldername is my directory on server containing file. well, you can minimize path to be exposed to querystring URL and add code to handler, it’s up to you.
Just you pass some parameter to handler via querystring or other method and capture it inside handler.
Here I’m sending relative foldername with filename to handler.
In code of step 2, first I get querystring value and combine “foldername/filename.extension” path to my main download directory.
In your case, it can be: Path.Combine(“~\downloads”,file)) in it will be r.(“path to the file”)
You can add authentication check code before you pop up dialog box and redirect to login.
Ok that’s all. Add comment if you have any question.
Thanks for reading.