File Download in Asp.Net with C#

Introduction

This code is provide a download functionality in Asp.Net with c#..

So to download any file in ASP.Net using C# import this namespace

Namespace

using System.Net;

Use the code

First we create source file using Button, TextBox and Label Control..

Enter path in Textbox

Example:-E-Book/HiFriends.doc

and download your file in your pc.

<body>
<
form id="form1" runat="server">
<
div>
<
table class="style1">
<
tr>
<
td style="text-align: right">Select Path :-&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
<
td><asp:TextBox ID="txtFileName" runat="server" Width="201px"></asp:TextBox></td>
</
tr>
<
tr>
<
td>&nbsp;</td>
<
td>&nbsp;</td>
</
tr>
<
tr>
<
td>&nbsp;</td>
<
td><asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Download" /></td>
</
tr>
</
table>
</
div>
</
form>
</
body>

This Code Write in your cs file 

protected void Download_Click(object sender, EventArgs e)
{

    try

    {
        string strURL = txtFileName.Text;
        WebClient req =
new WebClient();
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.ClearContent();
        response.ClearHeaders();
        response.Buffer =
true;
        response.AddHeader(
"Content-Disposition", "attachment;filename=\"" + Server.MapPath(strURL) + "\"");
        byte[] data = req.DownloadData(Server.MapPath(strURL));
        response.BinaryWrite(data);
        response.End();
    }

    catch
(Exception ex)
    {
    }
}

Ebook Download
View all
Learn
View all