In this example i'm explaining how to Download Files From Server In Asp.Net and display Save As dialog box when a hyperlink is clicked on the site.
I have created a folder on server and stored some sample files to download.
First we need to write code to display names of all the files saved in Files folder as hyperlinks so that user can download these files.
You can read to know how to Save Files In Sql Database And Download From GridView In Asp.Net
Write below mentioned code inPage_Load event of page where you want to display all the links with file names.
Add a new web form Default2.aspx in the soulution and write code mentioned below in Page_Load Event.
I have created a folder on server and stored some sample files to download.
First we need to write code to display names of all the files saved in Files folder as hyperlinks so that user can download these files.
You can read to know how to Save Files In Sql Database And Download From GridView In Asp.Net
Write below mentioned code inPage_Load event of page where you want to display all the links with file names.
C# CODE
01protected void Page_Load(object sender, EventArgs e)02 {03 DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Files"));04 int counter = 0;05 foreach (FileInfo file in directory.GetFiles())06 {07 HyperLink link = new HyperLink();08 link.ID = "Link" + counter++;09 link.Text = file.Name;10 link.NavigateUrl = "Default2.aspx?name="+file.Name;11 12 Page.Controls.Add(link);13 Page.Controls.Add(new LiteralControl("<br/>"));14 }15 }
VB.NET CODE
01Protected Sub Page_Load(sender As Object, e As EventArgs)02 Dim directory As New DirectoryInfo(Server.MapPath("~/Files"))03 Dim counter As Integer = 004 For Each file As FileInfo In directory.GetFiles()05 Dim link As New HyperLink()06 link.ID = "Link" & System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)07 link.Text = file.Name08 link.NavigateUrl = "Default2.aspx?name=" + file.Name09 10 Page.Controls.Add(link)11 Page.Controls.Add(New LiteralControl("<br/>"))12 Next13End SubAdd a new web form Default2.aspx in the soulution and write code mentioned below in Page_Load Event.
C# CODE
1protected void Page_Load(object sender, EventArgs e)2 {3 string fileName = Request.QueryString["name"].ToString();4 Response.ContentType = "application/octet-stream";5 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);6 Response.TransmitFile(Server.MapPath("~/Files/" + fileName));7 Response.End();8 }
VB.NET CODE
1Protected Sub Page_Load(sender As Object, e As EventArgs)2 Dim fileName As String = Request.QueryString("name").ToString()3 Response.ContentType = "application/octet-stream"4 Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)5 Response.TransmitFile(Server.MapPath("~/Files/" & fileName))6 Response.[End]()7End Sub

0 comments:
Post a Comment