Click here to Skip to main content
15,891,704 members
Articles / Web Development / ASP.NET
Article

How to download any file

Rate me:
Please Sign up or sign in to vote.
1.40/5 (14 votes)
13 Jun 20073 min read 36.3K   16   9
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/";<br />//don't use hard coded it is not recommended<br />private long fileSize = 0;<br />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.

<br />protected void Page_Load(object sender, EventArgs e)<br />{<br /> //check if query string set, contain our file id, and that file id integer value<br /> if(Request.QueryString.Count > 0 && Request.QueryString["fid"] != null && int.TryParse(Request.QueryString["fid"], out fileID) )<br /> {<br /> //after check we get our file information from datanase lets say following data [File Caption, File Name on server]<br /> //Clear all content output for buffer stream<br /> Response.Clear();<br /> //clear all header submitted by response<br /> Response.ClearHeader();<br /> Response.ClearContent();<br /><br /> //Add new page header to allow open save dialog<br /> //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<br /> Response.AddHeader("Content-Disposition", "attachment; filename=" + FileCaption.Replace(" ","_").Trim("'!@#$%^&*()_+".ToCharArray()) + FileNameOnServerName.Substring(file.Name.LastIndexOf(".")));<br /><br /> //Map file path to load path into dialog box stream<br /> string filePath = Server.Map(filesFolder + FileNameOnServer);<br /><br /> //Now we create stream object to get some information about file such as file size<br /><br /> System.IO.FileStream stream = null;<br /> <br /> try {<br /> stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);<br /> fileSize = stream.Length;<br /><br /> Response.AddHeader("Content-Length", fileSize.ToString());<br /> Response.ContentType = "application/octet-stream"; <br /> }<br /> catch {} <br /> finally<br /> {<br /> if ( stream != null )<br /> stream.Close();<br /> }<br /> <br /> //now pass file data into response<br /> try {<br /> Response.WriteFile(filePath, 0, fileSize);<br /> }catch{System.IO.Exception){} <br /><br /> Response.End();<br />}<br />

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


Written By
Software Developer (Senior) none
Palestinian Territory (Occupied) Palestinian Territory (Occupied)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProblem with '_' Pin
Member 42349944-Oct-10 5:42
Member 42349944-Oct-10 5:42 
AnswerRe: Problem with '_' Pin
Member 42349946-Oct-10 22:43
Member 42349946-Oct-10 22:43 
GeneralRe: Problem with '_' Pin
Mohm'ed Melhem8-Oct-10 0:41
professionalMohm'ed Melhem8-Oct-10 0:41 
QuestionReading from a Database Pin
Brian Graffius21-Sep-08 4:25
Brian Graffius21-Sep-08 4:25 
GeneralThanks and a few changes Pin
red25-Sep-07 2:55
red25-Sep-07 2:55 
GeneralOpen any file Pin
Govardhana Reddy28-Jul-07 4:21
professionalGovardhana Reddy28-Jul-07 4:21 
AnswerRe: Open any file Pin
Mohm'ed Melhem28-Jul-07 18:50
professionalMohm'ed Melhem28-Jul-07 18:50 
Generalthanks a lot Pin
ambot200727-Jun-07 2:20
ambot200727-Jun-07 2:20 
GeneralRe: thanks a lot Pin
Mohm'ed Melhem28-Jun-07 19:48
professionalMohm'ed Melhem28-Jun-07 19:48 

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

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