File downloading in ASP.Net using C#  

by ne on 2021-09-29 under C#/Php

For downloading a file in ASP.Net we application provides a class WebClient. This class contains method called DownloadData(), with file path as input parameter.

WebClient class is avaliable with anmespace System.Net. So to download any file in ASP.Net using C# import this namespace

protected void  btnDowmLoad_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)
    {
     }
}

Thanks