Download File to Browser in ASP.NET using VB.NET

In this article you will learn how you can download any type of file to the Browser.
  • 17580
 

Introduction
 
Following article is simply showing that how you can Download any type of file to the Browser. In which using Streams you can provide a file to the user for without the need for FTP or any interference of the Internet Information Server (IIS), when you will create your Web application you have also add a folder to your application that include the file you want to download.

Getting Started

  • First you simply create a new ASP.NET web application. 
  • Now right click on your project in solution explorer and click add new folder. A folder will be added to your project. Give name images to the folder. Now any file that you want to download copy and paste in this folder as I have added a file named (StateManagement.ppt). 
  • Specify the folder name and file name in the code's link tag. 
  • Now write the below code in Default.aspx.

    <a href="images/StateManagement.ppt">Download the file</a>
    <%@ Page language="vb" runat="server" explicit="true" strict="true" %>
    <script language="vb" runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
           Dim strRequest As String = Request.QueryString("file")
           If strRequest <> "" Then
                  Dim path As String = Server.MapPath(strRequest)
                  Dim file As System.IO.FileInfo = New System.IO.FileInfo(path)
                  If file.Exists Then
                         Response.Clear()
                         Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
                         Response.AddHeader("Content-Length", file.Length.ToString())
                         Response.ContentType = "application/octet-stream"
                         Response.WriteFile(file.FullName)
                         Response.End
                  Else
                         Response.Write("This file does not exist.")
                  End If
           Else
                Response.Write("Click link to download.")
           End If
    End Sub
    </script>
     
  • The Design mode of the Default.aspx page will look like below.

    File-Download.gif
     
  • Now run your application.
Output

File-Download2.gif

File-Download3.gif

File-Download4.gif

File-Download5.gif

File-Download6.gif

File-Download7.gif

Summary


In this article you learned how to Download any type of file to the Browser.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.