Download File in ASP.NET

To Downlaod a file, use following code…

First of all put all the files in a folder in solution explorer like this.


In Default.aspx Page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ‘’>

<html xmlns=’’&gt;
<head runat=”server”>
<form id=”form1″ runat=”server”>
<asp:RadioButtonList ID=”RadioButtonList1″ runat=”server”>
<asp:ListItem Value=”~/myfiles/Hydrangeas.jpg”>Hydrangeas Image</asp:ListItem>
<asp:ListItem Value=”~/myfiles/Jellyfish.jpg”>Jellyfish Image</asp:ListItem>
<asp:ListItem Value=”~/myfiles/aa.txt”>Text File</asp:ListItem>
<asp:ListItem Value=”~/myfiles/bb.docx”>Word File</asp:ListItem>
<asp:ListItem Value=”~/myfiles/cc.xlsx”>Excel File</asp:ListItem>

<br />
<asp:Button ID=”Button1″ runat=”server” Text=”Download”
onclick=”Button1_Click” />

In Default.aspx.cs Page.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected void Button1_Click(object sender, EventArgs e)

string file = RadioButtonList1.SelectedValue;

if ((file !=null)&&(file!=””))

string ext = “”;
ext = System.IO.Path.GetExtension(file);
Response.ContentType = ext;
Response.AddHeader(“content-disposition”, “attachment;filename=DemoFile” + ext);




We download different type of file and for user interface put them in RadioButtonList Control.
Response.ContentType is used to tell the type of your file, i.e. .txt, .docx etc.

Response.AddHeader() is used to put the header part to downloading window. In this line DemoFile is the name of file you want to add in header, it can any name.
In Response.WriteFile() method is used to write the content of file in client’s machine.

Note :- The file you want to download by user must be in your website…



Download Code


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s