Downloading files in ASP.NET using C#

Web design and development based in Royston, Hertfordshire, United Kingdom

Griffiths Web Design

Downloading files in ASP.NET using C#

07709 579517

michael@griffithswebdesign.com

Downloading files in ASP.NET using C#

By Michael Griffiths

Created: 20.06.2016 00:00:00, last updated: 01.01.1900 00:00:00

Downloading files in ASP.NET using C#

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 asp.net 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:

<%@ 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;
}
}

}

Inside the process request part of the generated code you will need to delete its current contents, i.e. these lines:

context.Response.ContentType = "text/plain"; context.Response.Write("Hello World");

Once you have deleted those lines add the following code, I will explain what it does after:


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!");


}

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:

<a href="Download.ashx?file=images/cat1.jpg">cat pic</a>


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, michael@griffithswebdesign.com
I look forward to hearing your thoughts.



About Michael Griffiths

Web Developer and Social Media Coach

Comments

Comment posted by: Michael Griffiths

02.12.2016 12:34:01

Thank you very much.

Comment posted by: Gatsy

19.07.2016 17:43:34

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