Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to download any file

0.00/5 (No votes)
13 Jun 2007 1  
In this article I will try to explain how we could build simple web user control to handle file download of any type it could be even HTML files.

Introduction

May be some of will say this old staff and there is hundreds of such article but may be there are true but what I did found speak in general not in details how to deal with Unicode files to download from server or multi segment file name problem epically with Firefox browser which cause lot of problems.

Background

During last couple days in I got a web project for one of our departments that contain download section provided file download for public and site members but there is was a little problem that they some times upload on site files in different formats, so there is a little problem with files with such format like htm, txt for example they open directly inside browser window which bad idea to have such option on download section. Then I decide to build web user control to force open save dialog on any browser web site open with, which I would like to provide some useful info about to you.

And I will try to focus on some problems that I faced during development of this web user control too.

Using the code

I will expect that ever one can add new user control to there own web project using any Microsoft .NET IDE. after we add this control and name it FileDownload we will go to code behind page because we will not need for GUI representation for our control.

inside our control we should specify couple of system constants and member variables:

private const string filesFolder = "~/docs/";
//don't use hard coded it is not recommended
private long fileSize = 0;
private int fileID = 0;

I will use hard coded file for easer understand, now after that we will go into Load event to handle with query string that hold our file id which user wants to download from our web site.


protected void Page_Load(object sender, EventArgs e)
{
//check if query string set, contain our file id, and that file id integer value
if(Request.QueryString.Count > 0 && Request.QueryString["fid"] != null && int.TryParse(Request.QueryString["fid"], out fileID) )
{
//after check we get our file information from datanase lets say following data [File Caption, File Name on server]
//Clear all content output for buffer stream
Response.Clear();
//clear all header submitted by response
Response.ClearHeader();
Response.ClearContent();

//Add new page header to allow open save dialog
//Where we set file name that appear to user downloaded file as it is caption and replaced spaces by (_) and removed any other special characters because both of them cause problems on firefox
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileCaption.Replace(" ","_").Trim("'!@#$%^&*()_+".ToCharArray()) + FileNameOnServerName.Substring(file.Name.LastIndexOf(".")));

//Map file path to load path into dialog box stream
string filePath = Server.Map(
filesFolder + FileNameOnServer);

//Now we create stream object to get some information about file such as file size

System.IO.FileStream stream = null;

try {
stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
fileSize = stream.Length;

Response.AddHeader("Content-Length", fileSize.ToString());
Response.ContentType = "application/octet-stream";
}
catch {}
finally
{
if ( stream != null )
stream.Close();
}

//now pass file data into response
try {
Response.WriteFile(filePath, 0, fileSize);
}catch{System.IO.Exception){}

Response.End();
}

After we set this code now we can use this control inside any page so we can handle file download on any browser type.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here