Results 1 to 10 of 10

Thread: Allow download of filenames with &'s in them

  1. #1

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Allow download of filenames with &'s in them

    I want to allow users to download files that have names containing & characters.

    We've escaped our way through the problem but cannot seem to get around one last obstacle.

    Here in Download.asp.vb we have

    Code:
    Imports System.IO
    
    Partial Class Clients_Download
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim ctx As HttpContext = HttpContext.Current
            Dim response As HttpResponse = ctx.Response
            Dim sFile As String = Request.QueryString("filename".ToString)
    
            ' Buffer to read 10K bytes in chunk:
            Dim buffer(10000) As Byte
            ' Length of the file:
            Dim length As Integer
            ' Total bytes to read:
            Dim dataToRead As Long
            ' Identify the file to download including its path.
            Dim filepath As String = sFile
            ' Identify the file name.
            Dim filename As String = System.IO.Path.GetFileName(filepath)
    
            Using iStream As New FileStream(filepath, System.IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
                ' Total bytes to read:
                dataToRead = iStream.Length
    
                response.ContentType = "application/octet-stream"
                response.AddHeader("Content-Disposition", "attachment; filename=" & filename)
    And here is where it fails - the attachment; filename= line.

    The filename vbl has the & character within it.

    The pop-up that appears in the browser window asking for where to save the file shows a filename WITHOUT the &'s.

    Here is the continuation of the code
    Code:
                ' Read the bytes.
                While dataToRead > 0
                    ' Verify that the client is connected.
                    If response.IsClientConnected Then
                        ' Read the data in buffer
                        length = iStream.Read(buffer, 0, 10000)
    
                        ' Write the data to the current output stream.
                        response.OutputStream.Write(buffer, 0, length)
    
                        ' Flush the data to the HTML output.
                        response.Flush()
    
                        ReDim buffer(10000) ' Clear the buffer
                        dataToRead = dataToRead - length
                    Else
                        'prevent infinite loop if user disconnects
                        dataToRead = -1
                    End If
                End While
    
                iStream.Close()
    
                'delete the file after downloading it
                If Request.QueryString("delfile") = "true" Then
                    'make sure it contains \temp\ dir
                    If sFile.Contains("\temp\") Then
                        File.Delete(sFile)
                    End If
                End If
                response.End()
            End Using
        End Sub

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  2. #2
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Allow download of filenames with &'s in them

    It works ok for me.

    I assume this is a typo,
    Dim sFile As String = Request.QueryString("filename".ToString)
    and should be changed to:
    Dim sFile As String = Request.QueryString("filename").ToString


    This is what I get, running your code as it is.

    In the first box, filename is in a label, so it assumes & as shortcut and shows as underscore. But in the actual box where I specify filename to save, I can see the "&" in filename.

    Name:  file-download-with-ampersand-in-filename1.JPG
Views: 141
Size:  57.6 KB

    Name:  file-download-with-ampersand-in-filename2.JPG
Views: 134
Size:  68.4 KB
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  3. #3
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: Allow download of filenames with &'s in them

    Hey,

    You can try your luck with HttpServerUtility.HtmlEncode Method. This will convert characters to their respective HTML Hex format.
    Show Appreciation. Rate Posts.

  4. #4
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Allow download of filenames with &'s in them

    BTW how big are your files? Why do you need to read/write in chunks?

    This code is a simple one-liner and has always worked for me:
    vb.net Code:
    1. Sub TransmitFile(ByVal fileName As String)
    2.     Response.ContentType = "application/octet-stream"
    3.     Response.AddHeader("Content-Disposition", "attachment; filename=""" & System.IO.Path.GetFileName(fileName) & """")
    4.     Try
    5.         Response.TransmitFile(fileName)
    6.     Catch ex As Exception
    7.         Response.Write(ex.ToString)
    8.     End Try
    9. End Sub
    10.  
    11. Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    12.     Dim fileName As String = "C:\Temp\abc&d.txt"
    13.     TransmitFile(fileName)
    14. End Sub
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Allow download of filenames with &'s in them

    I'd suggest the URLEncode instead... otherwise you'll get& in the file name. By URLEncoding it, you get the %XX where XX is the ascii code (for instance a space comes out as %20). the browser & client should be able to sort it out from there.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  6. #6

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Allow download of filenames with &'s in them

    @pradeep - I see the initial pop up has the D underlined - which is what a
    & character would do to a string - that stinks.

    but you are seeing the & character in the actual filename.

    What version of IE

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Allow download of filenames with &'s in them

    Quote Originally Posted by Pradeep1210 View Post
    BTW how big are your files? Why do you need to read/write in chunks?
    They are huge - we do multi GB uploads and downloads

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  8. #8
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Allow download of filenames with &'s in them

    Quote Originally Posted by szlamany View Post
    @pradeep - I see the initial pop up has the D underlined - which is what a
    & character would do to a string - that stinks.

    but you are seeing the & character in the actual filename.

    What version of IE
    IE Version is: 6.0

    Yep. That underscore appearing there looks like a bug to me. Maybe it has been fixed in the latter versions of IE, but I'm not sure. I never use it other than development work.

    Name:  ie6-version-number.JPG
Views: 137
Size:  30.7 KB
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  9. #9
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Allow download of filenames with &'s in them

    Quote Originally Posted by szlamany View Post
    They are huge - we do multi GB uploads and downloads
    OK. Then it makes a lot of sense to transfer file in chunks, otherwise just a handful of users can eat up all the server memory and maybe crash your server too.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  10. #10

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Allow download of filenames with &'s in them

    Quote Originally Posted by Pradeep1210 View Post
    OK. Then it makes a lot of sense to transfer file in chunks, otherwise just a handful of users can eat up all the server memory and maybe crash your server too.
    Which is exactly what was happening!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width