DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

ASP.Net Serve File For Download

  • submit to reddit
        Function I use to serve a file on the webserver to the client machine.

   ' sends file to browser for download
   Private Sub SendFile(ByVal strPath As System.String, ByVal strSuggestedName As System.String)

      Dim strServerPath As String
      Dim objSourceFileInfo As System.IO.FileInfo

      ' convert relative path to path on server machine
      strServerPath = Me.Server.MapPath(strPath)

      ' get fileinfo of source file
      objSourceFileInfo = New System.IO.FileInfo(strServerPath)

      ' if the file exists
      If objSourceFileInfo.Exists Then

         With Me.Response

            ' tell the browser what content type to expect
            .ContentType = "application/octet-stream"
            ' tell the browser to save rather than display inline
            .AddHeader("Content-Disposition", "attachment; filename=" & strSuggestedName)

            ' tell the browser how big the file is
            .AddHeader("Content-Length", objSourceFileInfo.Length.ToString)

            ' send the file to the browser

            ' make sure response is sent

            ' end response

         End With

      ' if the file does not exist

         ' show error page
         ThrowError("Application Error", "File Missing From Server")

      End If

   End Sub