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">
<head runat="server">
<title>Downloading
file using asp.net and C# title>
head>
<body>
<form id="form1" runat="server">
<div>
If file is in the same web server where web
application or website is running:
<br />
<asp:HyperLink ID="HyperLink1"
runat="server"
NavigateUrl="~/Downloads/Downloads.zip">Downloadasp:HyperLink>
<br />
OR
<br />
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="http://sitename/Download/Downloads.zip">Downloadasp:HyperLink>
<br />
<br />
programmatically downloading a file
from web server to client
<br />
<asp:LinkButton ID="Downloadfile" runat="server" OnClick="Downloadfile_Click">Downloadasp:LinkButton>
div>
form>
body>
html>
Default .aspx.cs page
using System;
using
System.Configuration;
using
System.Data;
using
System.Linq;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Xml.Linq;
using
System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void Downloadfile_Click(object
sender, EventArgs e)
{
HttpWebRequest
objRequest = (HttpWebRequest)WebRequest.Create("http://sitename/Download/Downloads.zip");
HttpWebResponse
objResponse = (HttpWebResponse)objRequest.GetResponse();
int
bufferSize = 1;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition:", "attachment; filename=Sample.zip");
Response.AppendHeader("Content-Length",
objResponse.ContentLength.ToString());
Response.ContentType = "application/download";
byte[]
byteBuffer = new byte[bufferSize
+ 1];
MemoryStream
memStrm = new MemoryStream(byteBuffer,
true);
Stream
strm = objRequest.GetResponse().GetResponseStream();
byte[]
bytes = new byte[bufferSize
+ 1];
while
(strm.Read(byteBuffer, 0, byteBuffer.Length) > 0)
{
Response.BinaryWrite(memStrm.ToArray());
Response.Flush();
}
Response.Close();
Response.End();
memStrm.Close();
memStrm.Dispose();
strm.Dispose();
}
}