In this article I will explain with an example, how to download a File on Button Click in ASP.Net using C# and VB.Net.
 
 
File Location
The following screenshot displays how the File is stored in a Folder (Directory) named Files within the Project Folder.
Download File on Button Click in ASP.Net using C# and VB.Net
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net Button control.
<asp:Button Text="Download File" runat="server" OnClick="DownloadFile" />
 
 
Namespaces
You will need to import the following namespace.
C#
using System.IO;
 
VB.Net
Imports System.IO
 
 
Downloading File on Button Click in ASP.Net
When the Download File Button is clicked, first the Content Type and the Header for the File are set and then the File is written to the Response Stream and then the Response is flushed.
Finally, the File is downloaded in the Browser.
C#
protected void DownloadFile(object sender, EventArgs e)
{
    //File to be downloaded.
    string fileName = "Mudassar_Khan.pdf";
 
    //Path of the File to be downloaded.
    string filePath = Server.MapPath(string.Format("~/Files/{0}", fileName));
       
    //Content Type and Header.
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
 
    //Writing the File to Response Stream.
    Response.WriteFile(filePath);
       
    //Flushing the Response.
    Response.Flush();
    Response.End();
}
 
VB.Net
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
    'File to be downloaded.
    Dim fileName As String = "Mudassar_Khan.pdf"
 
    'Path of the File to be downloaded.
    Dim filePath As String = Server.MapPath(String.Format("~/Files/{0}", fileName))
 
    'Content Type and Header.
    Response.ContentType = "application/pdf"
    Response.AppendHeader("Content-Disposition", ("attachment; filename=" + fileName))
 
    'Writing the File to Response Stream.
    Response.WriteFile(filePath)
 
    'Flushing the Response.
    Response.Flush()
    Response.End()
End Sub
 
 
Screenshot
Download File on Button Click in ASP.Net using C# and VB.Net
 
 
Demo
 
 
Downloads