C# Download File from Server to Client PC Code Example

Downloading a file from server is a common task for most of the applications. Such as client wants to offer free download, free newsletter etc. Here i will try to show you how we can write the code in C# Download File from Server to Client PC as well as how we can re use the code.

Focus Area:

  1. Download file from Server
  2. Re usability
  3. Security aspects
  4. File size limitations
  5. Few common errors
  6. Important links

 

C# Download File from Server to Local PC:

Let we have a folder structure in our virtual directory named “FileArchieve/Flowers”. Now from this folder I want to download a file named “Flowers.png”. To do that add a drag & drop a Link Button control in Default page. Now under the button click event write the below code:

C# Code to Download a File from Server:

        Response.ContentType = "APPLICATION/OCTET-STREAM";
        String Header = "Attachment; Filename=XMLFile.xml";
        Response.AppendHeader("Content-Disposition", Header);
        System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath("FileArchieve/Flowers/Flowers.png"));
        Response.WriteFile(Dfile.FullName);
        //Don't forget to add the following line
        Response.End();

VB.Net Code to Download a File:

        Response.ContentType = "APPLICATION/OCTET-STREAM"
        Dim Header As [String] = "Attachment; Filename=XMLFile.xml"
        Response.AppendHeader("Content-Disposition", Header)
        Dim Dfile As New System.IO.FileInfo(Server.MapPath("FileArchieve/Flowers/Flowers.png"))
        Response.WriteFile(Dfile.FullName)
        'Don't forget to add the following line
        Response.[End]()

Output:

Code example in c# download file from server

That’s it. Now you can download your required file from the server.

Re usability:

Lets you have to provide this option in 5 pages then is it viable for you to write same code in 5 pages. There are a lot of way for re usability but here i will show you the simplest way to achieve this. Add a class & modify this in the following way:

Asp.NET C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 

<summary>
/// Summary description for Downloader
/// </summary>


public static class Downloader
{
    public static void Download(string sFileName, string sFilePath)
    {
        HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
        String Header = "Attachment; Filename=" + sFileName;
        HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
        System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
        HttpContext.Current.Response.WriteFile(Dfile.FullName);
        HttpContext.Current.Response.End();
    }
    
}

VB.Net Code:

Imports Microsoft.VisualBasic

Public NotInheritable Class Downloader
    Private Sub New()
    End Sub
    Public Shared Sub Download(sFileName As String, sFilePath As String)
        HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM"
        Dim Header As [String] = "Attachment; Filename=" & sFileName
        HttpContext.Current.Response.AppendHeader("Content-Disposition", Header)
        Dim Dfile As New System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath))
        HttpContext.Current.Response.WriteFile(Dfile.FullName)
        HttpContext.Current.Response.[End]()
    End Sub
End Class

Now you can reuse the method from any page. The below code segment will show you how you can invoke this method from your Default.aspx page:

C# Code:

Downloader.Download("Flowers.png", "FileArchieve/Flowers/Flowers.png");

VB.Net Code:

Downloader.Download("Flowers.png", "FileArchieve/Flowers/Flowers.png")

Security Aspects:

In my previous article on Upload file i have discussed Security aspects & file size. To read Click Here.

Few common errors:

1. Could not find a part of the path……..
Solution: Make sure that you have specified the path correctly.

2. Access or permission denied…
Solution: Read Security aspects & file size from above link.

3. HTML text/code added in the last with my downloaded file.
Solution: You missed to add Response.End(); in your code.

Good to know:

http://www.west-wind.com/weblog/posts/76293.aspx
http://www.devarticles.com/c/a/ASP.NET/HTTP-File-Download-Without-User-Interaction-Using-.NET/1/
http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net
6 comments on “C# Download File from Server to Client PC Code Example
  1. Mohd Arshad says:

    .aspx .cs if (e.CommandName == “Download”) { Response.ContentType = “APPLICATION/OCTET-STREAM”; String Header = “Attachment; Filename=XMLFile.xml”; Response.AppendHeader(“Content-Disposition”, Header); System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath(“C:/Users/hp/Documents/Visual Studio 2010/WebSites/FileUpload/Files/budget_ldo.png”)); Response.WriteFile(Dfile.FullName); //Don’t forget to add the following line Response.End(); } Error ‘C:/Users/hp/Documents/Visual Studio 2010/WebSites/FileUpload/Files/budget_ldo.png’ is a physical path, but a virtual path was expected.

    • code display says:

      Please follow the code sample. Try using “Files/budget_ldo.png” within server.mappath() function.

  2. Jim Beck says:

    You’re the best, the code works great! How can I download to a specific file in users computer?

  3. Harvey Berman says:

    This didn’t work at first. There were security issues. Then, I added the following to my web.config file: The declaration solved all my problems. Everything worked great. Your solution was much better than anything else I could find on the web. Every other solution was very complicated, had security issues I couldn’t figure out, or both of the above. Many thanks for making this available. One question: Am I creating any problems for myself by setting the trust level to “Full”?

  4. Harvey Berman says:

    Oops! Part of my previous comment was deleted from this message, so I am re-sending it. Sorry for the confusion. This didn’t work at first. There were security issues. Then, I added the following to my web.config file: trust level=”Full”. The declaration solved all my problems. Everything worked great. Your solution was much better than anything else I could find on the web. Every other solution was very complicated, had security issues I couldn’t figure out, or both of the above. Many thanks for making this available. One question: Am I creating any problems for myself by setting the trust level to “Full”?

  5. Anju Patel says:

    Thank you so much…. This code is very nice and usefull in creating my project…to download file…thank you very much….and keep it up….

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*