View Light

HOWTO: Force file to download rather than open in browser

Some people have their browser set up to automatically open certain file types (Such a Excel .xls, and Word .doc files) INSIDE the browser (Using an embedded OLE object such as Word or Excell) rather than opening it in a 'real' instance of Excel or Word. For some things, this is a real headache, especially for less experienced user, as the normal Excel or Word menus/toolbars do not show on the screen.

If you don't want this to happen, the following code tweaks the download so that it skips over any 'open inside the browser' settings the user has set. You still get the 'Open', 'Save', 'Cancel' buttons, but the Open button now opens in the intended application rather than inside the browser!

The only drawback to this is that the default save directory is in the 'Temporary Internet Files' directory. If anyone has any ideas on how to override this (Maybe set to 'My Documents' instead, please post here!)

The code is as follows, you pass the file and directory in 'relative to the current directory' format, rather than an absolute file location (Aka: No drive letter). Such as download/somefile.xls rather than c:\inetpub\wwwroot\appname\download\somefile.xls)

    Private Sub ForceFileDownload(ByVal fname As String)

        Dim name As String = Path.GetFileName(fname)
        Dim ext As String = Path.GetExtension(fname)
        If (ext = "") Then
            fname = fname + ".txt"
            ext = ".txt"
        End If

        Dim type As String = ""
        If ((Not (ext = Nothing))) Then

            Select Case ext.ToLower()
                Case ".htm"
                    type = "text/HTML"
                Case ".html"
                    type = "text/HTML"
                Case ".txt"
                    type = "text/plain"
                Case ".doc"
                    type = "Application/msword"
                Case ".rtf"
                    type = "text/plain"
                Case ".csv"
                    type = "Application/x-msexcel"
                Case ".pdf"
                    type = "Application/pdf"
                Case ".xls"
                    type = "Application/x-msexcel"
                Case ".log"
                    type = "text/plain"
                Case Else
                    type = "text/plain"
            End Select

        End If

        Response.AppendHeader("content-disposition", "attachment; filename=" + name)
        If ((type <> "")) Then
            Response.ContentType = type
        End If

    End Sub
Rating: (You must be logged in to vote)
- Imports System.IO [Read 1565]
Comfortably Anonymous
10/21/2005 3:13:16 PM
0 Dislikes: 0