2014-07-15 131 views
0

有沒有辦法通過比較文件大小來檢查下載的文件是否已經存在? 以下是我的下載代碼。通過比較文件大小來檢查下載的文件是否存在

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 
+0

你的意思是你想避免下載不變的文件? – Alireza

+0

@Alireza我想避免下載已完全下載的文件。例如,文件a.zip大小爲160 kb,它被下載並且程序開始下載第二個文件但出現問題,因此用戶需要取消下載操作。然後用戶再次開始下載程序,這次程序會檢查File a.zip是否已經下載,如果是,那麼它會檢查文件大小。 – plokuun

回答

2

本地文件的大小可以使用來自System.IO命名空間中的FileFileInfo類來確定。要確定要通過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 
相關問題