Downloading Files C#

A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported.

C# Code

   // Get the physical Path of the file(test.doc)
   string filepath = Server.MapPath("test.doc");

   // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo file = new FileInfo(filepath);
 
   // Checking if file exists
   if (file.Exists)
   {
    // Clear the content of the response
    Response.ClearContent();
   
    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
   
    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());

    // Set the ContentType
    Response.ContentType = ReturnExtension(file.Extension.ToLower());

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);

    // End the response
    Response.End();
   }

private string ReturnExtension(string fileExtension)
{
     switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
}

N.B:  If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below code

Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

Response.TransmitFile VS Response.WriteFile:
 1- TransmitFile: This method sends the file to the client without loading it to the Application memory on the server. It is the ideal way to use it if the file size being download is large.
 2- WriteFile: This method loads the file being download to the server's memory before sending it to the client. If the file size is large, you might the ASPNET worker process might get restarted.

Hope this helps,

Comments

# re: Downloading Files C#

Friday, April 20, 2007 9:50 AM by JoshStodola

Response.End() calls Response.Flush().

Therefore, you only need to call Response.End

# re: Downloading Files C#

Friday, April 20, 2007 11:35 AM by JoshStodola

Also, you better clear the headers or you will never be able to open the file in IE6 without saving it first!

# re: Downloading Files C#

Thursday, May 10, 2007 9:05 AM by JTang

Thank you for your advice. I tried your code and I could be able to download a file to my local PC. However, when I try to open the file instead of saving it, I could see that it is downloading. After the downloading is done, the MS Word popped up an error message saying:

The file could not be found.

Try one or more of the following:

* Check the spelling of the name of the document.

* Try a different file name.

(C:\...\test[1].doc)

Would you help me to solve this issue?

Thank you very much.

# re: Downloading Files C#

Saturday, May 12, 2007 7:00 AM by haissam

Hello Jtang,

Please send me your code to my email to check it out

Best Regards,

HC

# re: Downloading Files C#

Thursday, May 24, 2007 10:57 PM by Manish

Thanks for this code. i was stuct in my project for this problem since yesterday. thank u very much

# re: Downloading Files C#

Thursday, May 31, 2007 1:03 AM by Vinod

Thank u for ur help, this will help me out only for single file to downlod.

i want n number of selected files  to download  at a time.

how can i?

tHANKING YOU IN ADVANCE

mail me the code to vinod.vbv@gmail.com

# re: Downloading Files C#

Tuesday, June 05, 2007 6:30 AM by Neil

Hi Haissam,

Did you have any luck solving Jtang's problem? I'm having the same trouble, and I was hoping you could publish a fix for me and anyone else with the same problem.

Thanks very much!

Neil.

# re: Downloading Files C#

Tuesday, June 05, 2007 8:15 AM by haissam

Can you send your project to my inbox to test what is going on and how to fix it!

haissam@dotnetslackers.com

Best Regards,

# re: Downloading Files C#

Thursday, June 14, 2007 7:26 AM by bhushan

hi all.

plz give me solution on following problem.

how to execute code or display any message after comlete downloading file.

# re: Downloading Files C#

Monday, June 18, 2007 4:44 AM by varun

hi this code is working in a simple web from but this code throw error when u try that code in Model Dialog from(popup) in case of target ="_self".

plz advice

# re: Downloading Files C#

Wednesday, July 18, 2007 4:42 AM by haissam

Varun which type of error you are facing!! just email me the project and your problem...

# re: Downloading Files C#

Monday, July 23, 2007 10:28 PM by LingZ

Thank you, I have tested the code, for saving file, it works ok.

But for opening (in IE6), the word editor doesn't show up, only the xml scripts are displayed in IE.

Here's my code:

           string fileName = @"D:\rptTest\AspNet_Html\WordInHtml\WordInHtml\output\report.xml";

           Response.Clear();

           Response.ClearHeaders();

           Response.ClearContent();            

           Response.AddHeader("Content-Disposition", "attachment;filename=new.xml");

           Response.ContentType = "application/ms-word";

           Response.WriteFile(fileName);          

           //Response.Flush();

           Response.End();

# re: Downloading Files C#

Wednesday, September 19, 2007 7:33 AM by Jhed

i have a project, i make a intranet webpage i use c# in my script, i page for uploading a file, then i want to view the file that i upload and download it can u help with the script . can you help me. yo can reply me in email add jhd_nightfire@yahoo.com

# re: Downloading Files C#

Tuesday, September 25, 2007 9:35 AM by Navin S.

Hi,

I'm new to C# and I just wanted to know what a response is?

Thank you!

navinsukhdeo@gmail.com

# re: Downloading Files C#

Thursday, September 27, 2007 11:14 AM by Claudio V

Hello,

Is there a way to make this code work for files located in a network drive? This would be for a web application that runs only in the intranet.

# re: Downloading Files C#

Tuesday, October 09, 2007 2:57 AM by Kaladevi

Hi,

   I'm also facing the same problem (ie)

The file could not be found.

Try one or more of the following:

* Check the spelling of the name of the document.

* Try a different file name.

(C:\...\Sample[1].doc)

Please let me know the solution.

# re: Downloading Files C#

Tuesday, October 09, 2007 11:25 AM by Chicago_Lar

A note on Response.End() versus Response.Flush().

The Microsoft documentation says that Response.End() calls Response.Flush() if Response.Buffer =is set to true. E.g.,

Response.Buffer = true;

Response.End();

Also, newbies (like me) who wish to convert the code Haissam graciously provided into a C# class, may need to add the following two lines to the C# class code file:

using System.Collections;

using System.IO;

Visual Studio adds these to a code behind file, in my version (VWDE 2008 beta) did not automatically add them to the class file in the App_Code folder.

# re: Downloading Files C#

Tuesday, October 09, 2007 3:40 PM by haissam

Chicago_lar your comment is appreciated....

# re: Downloading Files C#

Thursday, November 01, 2007 3:28 AM by Rajesh

Your code is help to me

Thanks

# re: Downloading Files C#

Friday, November 16, 2007 6:14 AM by Sunny

Wonderful post Helped a lot ! Thanks

# re: Downloading Files C#

Tuesday, November 27, 2007 4:54 PM by butters

Worked for me.  I'd also like to add that if you want to delete the file after it has downloaded, then change response.end to response.close then do a delete

response.close();

file.delete();

# re: Downloading Files C#

Monday, December 10, 2007 7:32 PM by alv

Hi, I would like to know how to download files if I know the directory, but not the filename?

# re: Downloading Files C#

Wednesday, December 19, 2007 12:07 AM by nellai

best

# re: Downloading Files C#

Monday, December 31, 2007 3:59 AM by Premanand

It is working

but while downloading it converts " " into

"_" it is not requirement

# re: Downloading Files C#

Tuesday, January 08, 2008 8:34 AM by Christo

At last!! Posted code that works!!  I just dont get what application/ms-word is for?  I can save pdf and exe files.

Anyway, thanx a lot!

Christo

# re: Downloading Files C#

Tuesday, January 08, 2008 8:59 AM by haissam

We assign "application/ms-word" to the response content type property to tell the browser that the content is a microsoft word.

# re: Downloading Files C#

Tuesday, January 08, 2008 9:52 AM by Christo

Ok, but why does it still work, even if it is not a .doc file?

# re: Downloading Files C#

Wednesday, January 09, 2008 5:43 AM by nitin

very good article ,it helped me a lot ,thanks for the same.

# re: Downloading Files C#

Sunday, January 13, 2008 8:48 PM by alv

hi, i would like to download multiple file. may i know how can i do that?

# re: Downloading Files C#

Monday, January 14, 2008 5:46 AM by Manmohan

Very Good article. It solved my problem instantly.. Thanks for such a helpful article.

# re: Downloading Files C#

Monday, January 14, 2008 6:23 AM by Christo

You can add them into a zip or rar and just download that.  Or use a download manager that can download multiple files.  No other help, sorry

# re: Downloading Files C#

Tuesday, January 15, 2008 2:45 PM by haissam

The code above works perfectly however for best practices i recommend to use Response.TransmitFile instead of Response.WriteFile. The only difference between these two is

1- Response.WriteFile: Buffers the file to the server memory before being sent to the client

2- Response.TransmitFile: send the file to the client without buffering.

# re: Downloading Files C#

Friday, January 25, 2008 11:13 AM by Ruchir

thanks, ur code was very helpfull, but there is one question, i am able to save a file but not able to open it in browser, can u help me in this . I m getting error as file is corrupted.

# re: Downloading Files C#

Thursday, January 31, 2008 7:15 AM by Mansoor

Hey thank you.......Thanks for the code.I was worried how to do and to my luck i found it and that too without much difficulty you delivered the code. Keep going.

# re: Downloading Files C#

Thursday, January 31, 2008 7:18 AM by Humaira

hi Haissam!

im making a project in which a user can download file which i have saved in my database table. how can i?

# re: Downloading Files C#

Monday, February 04, 2008 7:06 AM by anisia

the method is very nice but I would like to know how to do a download without using the Response object.THKS a Lot

# re: Downloading Files C#

Monday, February 04, 2008 4:16 PM by haissam

Ruchir

Please send me by email the code you are working and on which file type this error is generated

# re: Downloading Files C#

Monday, February 11, 2008 8:31 PM by jl

Haissam, I reviewed the code you posted and had a couple questions that stem from a problem I found.  The problem was non-existent in IE7 but when using IE6 when I click on the "Save" button on the save file dialog it said the file was missing.  I noticed at the top a gentlemen named JoshStodola said the header needs to be cleared.  I call Response.Clear() but wasn't sure if that included clearing the header as well.  I now added Response.ClearHeaders() along with Response.ClearContent().

I'm wondering what the intricacies of this are in terms of whether it is the solution I'm looking for and also what it is that causes this different behavior in IE6.

Thanks

# re: Downloading Files C#

Wednesday, February 13, 2008 7:00 AM by haissam

anisia you could use the WebClient class to download the file

msdn2.microsoft.com/.../system.net.webclient.aspx

# re: Downloading Files C#

Thursday, February 14, 2008 1:41 PM by arno

how do you do when you do not know the content type of file.

My website allow users to upload any type of file and then a link is created to download  those files.

So how do I  configure the contenttype in this case?

# re: Downloading Files C#

Thursday, February 14, 2008 5:06 PM by haissam

You can set a predefined list of the popular content types. you get the file extension and using a switch statement u set the content type.

It is a basic idea, i will try to find a more generic way.

# re: Downloading Files C#

Friday, February 15, 2008 2:14 AM by alter

your code for bypassing Open/Save/Cancel dailog box does not work on IE7..

got idea?..thanks

# re: Downloading Files C#

Friday, February 15, 2008 12:22 PM by lavanya

thank you for your code. i think it will help me a lot.

# re: Downloading Files C#

Thursday, February 21, 2008 12:43 AM by Vimal

Hi Haissam,

Your code is working perfectly when i am running the application from Dotnet, but the same pdf when i am trying to open from my Localhost (i.e from IIS) i am getting the following error:

Adobe Reader could not open '2_21_2008doc[1].pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).

Please suggest some solution for this problem!!

# re: Downloading Files C#

Thursday, February 21, 2008 11:12 AM by Nodirbek

Hi,

I have same problem ['test[1].pdf' because it is either not a supported file type or because the file has been damaged] when i try to delete the file after WriteFile method. I couldn't delete file even by Async call.

Here is part of my code :

delegate void BeginWriteFile(string filename);

private void SendFile()

{

  .....

  BeginWriteFile writeasync = new  BeginWriteFile(context.Response.WriteFile);

       writeasync.BeginInvoke(path, delegate(IAsyncResult result) { if(result.IsCompleted)System.IO.File.Delete(path); }, null);

}

Thanks.

# re: Downloading Files C#

Tuesday, February 26, 2008 5:40 PM by Lorin

would changing the content type to "application/octet-stream" make it more general purpose?

# re: Downloading Files C#

Thursday, February 28, 2008 8:48 AM by haissam

application/octet-stream is a general content type which is Binary.

# re: Downloading Files C#

Wednesday, March 12, 2008 1:20 AM by ashis

thanks it excellent code , it works with me.

I am novice programmer, it helps too much for my day to day tasks.

keep on writing.

thanks

# re: Downloading Files C#

Monday, March 24, 2008 11:54 AM by Michael

Can you translate this code to VB?

# re: Downloading Files C#

Monday, March 24, 2008 2:37 PM by Wango

Haissam,

thanks for the code and hint.  What I actually wanted was to be able to splash the MS Word document into a browser without. What I am getting from your code is the ability to programatically open or save a word document after being prompted to do so.

The reason I am asking for this functionality is because I do not want to tamper with the application everytime the contents of a document changes.

Do you have code that can accomplish that?

Thanks,  Wango

# re: Downloading Files C#

Monday, March 24, 2008 7:25 PM by haissam

Michael,

There are some online tools you can use to convert codes between c# and VB.NET. below is a good link

labs.developerfusion.co.uk/.../csharp-to-vb.aspx

# re: Downloading Files C#

Tuesday, March 25, 2008 10:58 AM by Wango

haissam,

was I was looking for is code that can grab an MS Word document or any other document and splash it on the browser while retaining the format!

If an MS Word doc contains the following:

Company News

We'll add some news later.

Company Events

We'll add company events later.

I would like to lay my hands on code that would grab that file and produce the same results as the code caption below would produce:

 <h1>Company News</h1>

 <p>We'll add some news later.</p>

 <h1>Company Events</h1>

 <p>We'll add company events later.</p>

In other words, I want to avoid writing HTML tags as above.

Wango.

# re: Downloading Files C#

Saturday, March 29, 2008 3:16 AM by haissam

Wango, Please email me the code you are using and the exact details of what you are trying to achieve in order to be able to help.

Regards,

# re: Downloading Files C#

Wednesday, May 07, 2008 4:22 AM by vijay garg

I am getting error while trying to open the file as:

File could not be found. Check the spelling of the file name... But surprisingly if i save the file there are no issues. Please help.

Here is my sample code:

FileInfo file = new FileInfo(fileCompletePath);

HttpResponse response = HttpContext.Current.Response;

response.ClearContent();

response.ClearHeaders();

response.AppendHeader("Content-Disposition:", "attachment; filename =" + file.Name);

response.AppendHeader("Content-Length:", file.Length.ToString());

response.ContentType = "application/vnd.ms-excel";

response.TransmitFile(fileCompletePath);

response.Flush();

response.End();

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.