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
ASP.Net Serve File For Download
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
.WriteFile(objSourceFileInfo.FullName)
' make sure response is sent
.Flush()
' end response
.End()
End With
' if the file does not exist
Else
' show error page
ThrowError("Application Error", "File Missing From Server")
End If
End Sub




