Search code examples
vb.netwebclientsystem.netdownloadfileasync

Unable to complete download using DownloadFileAsync


I am trying to download a file using simple basic webclient instructions, however the file is not downloading completing. If I am trying to download a 10mb/100mb file, it either downloads a 7kb file or an empty file. I am just using a ProgressBar to show the download progress. Here is the code that I am using.

Imports System.Net

Public Class Form1

    Dim WithEvents wc As New WebClient

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        wc.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), "100mb.test")
End Sub

Private Sub wc_DownloadFileCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs) Handles wc.DownloadFileCompleted
    ProgressBar1.Visible = False
    ProgressBar1.Value = 0
End Sub

Private Sub wc_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles wc.DownloadProgressChanged
    ProgressBar1.Visible = True
    ProgressBar1.Value = e.ProgressPercentage
End Sub

End Class

Solution

  • Finally, I found a solution via this forum. I just added headers to the webclient and it worked fine. Here is the code for other's reference.

    wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)")
    

    Add it before calling the DownloadFileAsync function.