TIP: File download using ASP.NET

The following is a method to send a file to browser using ASP.NET
 
Dim fs As FileStream
Dim strPath = "C:\DownloadableFilePath\"
Dim strFileName As String = "Filename.pdf"
fs = File.Open(strPath & strFileName, FileMode.Open)
Dim bytBytes(fs.Length) As Byte
fs.Read(bytBytes, 0, fs.Length)
fs.Close()
Response.AddHeader("Content-disposition", "attachment; filename=" & strFileName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(bytBytes)
Response.End() ‘or Response.Redirect("somepage.aspx",false)
 
Alternatively, you can also use (if it is available within web application folders) with WriteFile() as follows
 
Public Sub SecureFileDownload(ByVal inFile As String)
    Dim strFileNamePath As String
    strFileNamePath = Request.MapPath("SecureDirectory") & "\" & inFile
    Dim myFile As FileInfo = New FileInfo(strFileNamePath)
    Response.Clear()
    Response.AddHeader("Content-Disposition", "attachment; filename=" & myFile.Name)
    Response.AddHeader("Content-Length", myFile.Length.ToString())
    Response.ContentType = "application/octet-stream"
    Response.WriteFile(myFile.FullName)
    Response.End()
End Sub
 
thanks
Jag

About Jag

.NET Architect
This entry was posted in ASP.NET and tagged , . Bookmark the permalink.