Griffiths web design based in Royston, Hertfordshire, United Kingdom


Downloading files in ASP.NET using C#

Author:   Michael Griffiths

Date created:   20 June 2016

[l]In this article I will be discussing with you how to download files from the server. We will be creating a Generic Handler to do all the heavy lifting. That way the code can be re-used whenever and wherever it is needed. As usual I recommend creating a new website to play around in, so open up visual studio and create a new empty website (File > new > website) or (Shift + Alt + N) In your shiny new website we need to add a generic handler, so go to (website > add new item) or (Ctrl + Shift + A) Select Generic Handler from the list, I called mine Download.ashx. Visual studio will do some of the hard work for you by generating the following code: [/l][code]<%@ WebHandler Language="C#" Class="Download" %> using System; using System.Web; public class Download : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } [/code] [l]Inside the process request part of the generated code you will need to delete its current contents, i.e. these lines: [/l] [code]context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); [/code][l]Once you have deleted those lines add the following code, I will explain what it does after:[/l] [code]string file = context.Request.QueryString["file"]; if (!string.IsNullOrEmpty(file) && File.Exists(context.Server.MapPath(file))) { context.Response.Clear(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(file)); context.Response.WriteFile(context.Server.MapPath(file)); // This would be the ideal spot to collect some download statistics and / or tracking // also, you could implement other requests, such as delete the file after download context.Response.End(); } else { context.Response.ContentType = "text/plain"; context.Response.Write("File not be found!"); } [/code] [l]What does this code do? Well I’m glad you asked. First it creates a string from the query string value, which is the file to be downloaded by the user. Next it checks to make sure the newly created string is not empty and that the file exists, if it passes these checks the code can move on but if not the code takes you to the else block which informs the user that the file cannot be found. Now the interesting stuff happens. First we clear the output before we fill it in case there is any data lurking around in there that we’ve forgotten about. Next we set the content type to ‘application/octet-stream’ which is a binary file, that way all file types are covered. Then we move onto the next line, ‘AddHeader(("content-disposition", "attachment;filename=" + Path.GetFileName(file))’. This lets the user save the file to their computer and then decide how to use it, instead of the browser trying to use the file. Next we write the file then call Response.End(), which sends all currently buffered output to the client, stops execution of the page, and raises the System.Web.HttpApplication.EndRequest event. To use the generic handler we have just created you will need to add a link into your webform, like so: [/l][code]cat pic[/code] [l] As you can see you link to the Download.ashx file with a query string that informs the code which file the user wishes to download, in this case it is an image file called cat1.jpg which resides in a folder called images. That is all there is to it. Easy to implement, reusable code. Wonderful isn’t it? Now you can start offering some downloadable goodies to your website users. I hope you found this article helpful and informative. If you have any comments, questions, queries etc. then please feel free to comment below or get in touch via email, I look forward to hearing your thoughts. [/l]

About the author

My name is Michael Griffiths, I am a website designer and developer and the owner of Griffiths Web Design. I am based in Royston, Hertfordshire. Most of my work is local, Hertfordshire, Cambridgeshire, Bedfordshire, Essex etc. but that’s not to say I won’t work elsewhere. One of the wonders of modern technology is remote working. So no matter where the client is located it is always possible to connect.

I specialise in creating ASP.NET webforms applications using C#. I use Microsoft SQL Server for database development and on the front end I use Html, CSS and JavaScript. I am also proficient in the use of jQuery and several CSS frameworks.

One of my greatest passions in life is learning. Which is why I chose to pursue a career in web design and development, technology is in a state of constant and rapid evolution which means there is always something new to learn. I also enjoy writing, both fiction and non-fiction.


Please feel free to leave a comment below:


Damn, I wish I could think of sotnehimg smart like that!

Michael Griffiths

Thank you very much.

Griffiths Web Design Logo by Michael Griffiths
Griffiths Web Design Logo by Michael Griffiths
Click to go to the top of the page