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.

se

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” ‘http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd’>

<html xmlns=’http://www.w3.org/1999/xhtml’&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<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>
</asp:RadioButtonList>

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

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);
Response.WriteFile(file);
Response.End();

}

}
}

Here,

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…

Output

ot

Download Code

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s