0

Is there a way to check a downloaded file is already exists by comparing it's file size? Below is my download code.

Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
    Dim TestString As String = "http://123/abc.zip," & _
        "http://abc/134.zip,"
    address = TestString.Split(CChar(",")) 'Split up the file names into an array
    'loop through each file to download and create/start a new BackgroundWorker for each one
    For Each add As String In address
        'get the path and name of the file that you save the downloaded file to
        Dim fname As String = IO.Path.Combine("C:\Temp", IO.Path.GetFileName(add))            
        My.Computer.Network.DownloadFile(add, fname, "", "", False, 60000, True) 'You can change the (False) to True if you want to see the UI
        'End If
    Next
End Sub
plokuun
  • 51
  • 8
  • You mean you want to avoid downloading unchanged files? – Alireza Jul 15 '14 at 05:57
  • @Alireza I want to avoid downloading a file that has been fully downloaded. For example File a.zip size 160 kb and it was downloaded and the program starts to download the second file but has a problem so the user needs to cancel the download operation. Then the user starts to download process again, this time the program will check if File a.zip has been download or not and if it yes then it will check the file size. – plokuun Jul 16 '14 at 01:48

1 Answers1

2

The size of a local file can be determined using the File or FileInfo class from the System.IO namespace. To determine the size of a file to be downloaded by HTTP, you can use an HttpWebRequest. If you set it up as though you were going to download the file but then set the Method to Head instead of Get you will get just the response headers, from which you can read the file size.

I've never done it myself, or even used an HttpWebRequest to download a file, so I'm not going to post an example. I'd have to research it and you can do that just as easily as I can.

Here's an existing thread that shows how it's done in C#:

How to get the file size from http headers

Here's a VB translation of the code from the top answer:

Dim req As System.Net.WebRequest = System.Net.HttpWebRequest.Create("https://stackoverflow.com/robots.txt")
req.Method = "HEAD"
Using resp As System.Net.WebResponse = req.GetResponse()
    Dim ContentLength As Integer
    If Integer.TryParse(resp.Headers.Get("Content-Length"), ContentLength)
        'Do something useful with ContentLength here 
    End If
End Using

A better practice would be to write this line:

req.Method = "HEAD"

like this:

req.Method = System.Net.WebRequestMethods.Http.Head
Community
  • 1
  • 1
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46