通过比较文件大小来检查下载的文件是否存在

时间:2014-07-15 05:42:36

标签: vb.net download backgroundworker

有没有办法通过比较文件大小来检查下载的文件是否已经存在? 下面是我的下载代码。

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

1 个答案:

答案 0 :(得分:2)

可以使用File命名空间中的FileInfoSystem.IO类来确定本地文件的大小。要确定HTTP要下载的文件的大小,您可以使用HttpWebRequest。如果您将其设置为要下载文件,但将Method设置为Head而不是Get,则只会获得响应标头,您可以从中读取文件大小。

我自己从未这样做过,甚至没有使用HttpWebRequest来下载文件,因此我不打算发布示例。我必须研究它,你可以尽我所能地做到这一点。

这是一个现有的帖子,展示了它在C#中的表现:

How to get the file size from http headers

这里是来自顶部答案的代码的VB翻译:

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

更好的做法是写下这一行:

req.Method = "HEAD"
像这样:

req.Method = System.Net.WebRequestMethods.Http.Head