Download File From Server In Asp.Net

Download files from server in asp.net
Download files from server or hyperlink in asp.net

In this post i'm explaining how to download a file from server in asp.net and display Save As dialog box when a link is clicked on the site.

For this example i have created a folder named Files on the server and stored Some sample files to download.

First we need to write code to display names of all the file saved in Files folder as hyperlinks so that user can download these files.


Write below mentioned code in Page_Load event of page where you want to display all the links with file names.



C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Files"));
        int counter = 0;
        foreach (FileInfo file in directory.GetFiles())
        {
            HyperLink link = new HyperLink();
            link.ID = "Link" + counter++;
            link.Text = file.Name;
            link.NavigateUrl = "Default2.aspx?name="+file.Name;
            
            Page.Controls.Add(link);
            Page.Controls.Add(new LiteralControl("<br/>"));
        }
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim directory As New DirectoryInfo(Server.MapPath("~/Files"))
 Dim counter As Integer = 0
 For Each file As FileInfo In directory.GetFiles()
  Dim link As New HyperLink()
  link.ID = "Link" & System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
  link.Text = file.Name
  link.NavigateUrl = "Default2.aspx?name=" + file.Name

  Page.Controls.Add(link)
  Page.Controls.Add(New LiteralControl("<br/>"))
 Next
End Sub

Add a new web form Default2.aspx in the soulution and write code mentioned below in Page_Load Event.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string fileName = Request.QueryString["name"].ToString();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.TransmitFile(Server.MapPath("~/Files/" + fileName));
        Response.End();
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim fileName As String = Request.QueryString("name").ToString()
 Response.ContentType = "application/octet-stream"
 Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
 Response.TransmitFile(Server.MapPath("~/Files/" & fileName))
 Response.[End]()
End Sub

Build and run the code.

Download Sample Code



If you like this post than join us or share

0 comments: