How to retrieve and download server files (File.Exists and URL)

I have a database table where the user marks files to be downloaded. Subsequently, I browse this table and need to create a fileList to pass to an ActiveX downloader. My routine works locally and on the server for ONLY the first file. I know my logic must be bad, but I cannot find it. All of these files are always in the same server directory which is as follows: “D:\inetpub\vhosts\\sessionVideos\”

Sub (GetFileList)
Dim dtVideosSelected As New DataTable
Dim drVideosSelected As New DataRow
Dim strSourceDirectory As String = "sessionVideos/"
Dim strServerBasePath As String = Server.MapPath(strSourceFileDirectory)
Dim strFileName As String
Dim fileInfo As System.IO.FileInfo
Dim i As Int16

Response.ContentType = "text/plain"
Response.Charset = "UTF-8"

i = 0
Do While i < dt VideosSelected.Rows.Count
    drVideosSelected = dtVideosSelected.Rows(i)
    strFileName = drVideosSelected("VID_FileName")
    If File.Exists(strServerbasePath & strFileName)
        fileInfo = New System.IO.FileInfo(strServerbasePath & strFileName)
        Response.Write("*/* | " & fileInfo.Length & " | " & fileInfo.Name & " | ")
        Response.Write(EncodeFileName(strSourceFileDirectory & fileInfo.Name) & vbCr
            & vbLf)
    End If
    i += 1

End Sub

Private Function EncodeFileName(ByVal fullPath As String) As String
    Return Server.UrlEncode(fullPath).Replace("+", "%20").Replace("%2f", "/")
End Function

I have tried a lot of different things with no success.


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

To download a file,

Dim b() As Byte = System.IO.File.ReadAllBytes(strServerbasePath & strFileName)
Response.AddHeader("Content-Type: application/octate-stream")
Repponse.AddHeader("Content-Length: " & b.Length)
Response.AddHeader("Content-Disposition: attachment; filename=" & strFileName)

Solution 2

Ok, we have an answer…. I actually had double file extensions on the files that were not working but the option to hide known extensions was turned on (I guess by default). The .avi files looked the same as the others so I guess it was considering .avi to be an “unknown” file type. Whatever!

The answer is on my other post here:

Why is FileInfo showing an extra file extension?


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply