Atlanta Custom Software Development 

   Search        Code/Page

User Login



Forgot the Password?
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
» Regular Expr Tester
» Free Tools

How to force file download using code in

Total Hit ( 5425)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article



Many times we have requirement to popup file download dialogbox instead of user clicking on a link. This little code you can use in your ASPX page. Call the following method from your code which should prompt a file download dialogbox in user's browser.

Click here to copy the following block
Public Sub DownloadFile(ByVal fname As String, ByVal forceDownload As Boolean)
  Dim path As System.IO.Path
  Dim strMSG As String
  Dim fullpath = fname
  Dim name = path.GetFileName(fullpath)
  Dim ext = path.GetExtension(fullpath)
  Dim type As String = ""

  If Not IsDBNull(ext) Then
    ext = LCase(ext)
  End If

  Select Case ext
    Case "doc"
      type = "application/ms-word"
    Case "dot"
      type = "application/ms-word"
    Case "exe"
      type = "application/octet-stream"
    Case "xls"
      type = "application/ms-excel"
    Case "ppt"
      type = "application/ms-powerpoint"
    Case "pps"
      type = "application/ms-powerpoint"
    Case "txt"
      type = "text/plain"
    Case "htm"
      type = "text/html"
    Case "html"
      type = "text/html"
    Case "pdf"
      type = "application/pdf"
    Case "rtf"
      type = "application/rtf"
    Case "zip"
      type = "application/x-zip-compressed"
    Case Else
      type = "application/unknown"
  End Select

    If type <> "" Then
      System.Web.HttpContext.Current.Response.ContentType = type
    End If

    If (forceDownload) Then
      System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + name)
      System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "inline; filename=" + name)
    End If

  Catch ex As Exception
    strMSG = "File can't be downloaded at this time. Please try again later."
    'Response.Redirect("downloaderror.aspx?msg=" & strMSG & "&id=" & nProjectId)
  End Try
End Sub

Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with, SQL Server and other MS technologies. He is, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )

Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.