2013-03-10 99 views
-1

我正在製作一個自動文件下載器,我需要它來重新下載並覆蓋文件,當我按下按鈕時。如何覆蓋下載的文件vb.net

這裏是我的代碼:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    My.Computer.Network.DownloadFile _ 
    ("http://www.randomurl.com/randomfile.txt", _ 
    Path.Combine(Environment.GetFolderPath(_ 
    Environment.SpecialFolder.ApplicationData), _ 
    "test/randomfile.txt")) 
End Sub 

回答

1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
    Dim uri As System.Uri = New System.Uri("http://www.randomurl.com/randomfile.txt") 
    Dim webclient As System.Net.WebClient = New System.Net.WebClient() 

    Dim path As String = New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\\randomfile.txt")) 
    Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(path) 
    If Not System.IO.Directory.Exists(fileInfo.Directory.FullName) Then 
     System.IO.Directory.CreateDirectory(fileInfo.Directory.FullName) 
    End If 

    AddHandler webclient.DownloadFileCompleted, AddressOf webclient_DownloadDataCompleted 

    webclient.DownloadFileAsync(uri, path) 

End Sub 


Private Sub webclient_DownloadDataCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) 

    MessageBox.Show("Your download has completed.") 

End Sub 

(編輯 - 更改爲顯示在意見中的要求異步方法),該文件將是否被覆蓋

注它存在 - >http://msdn.microsoft.com/en-us/library/ez801hhe(v=VS.80).aspx

+0

有人可以通過DownloadFileAsync獲取代碼嗎? – TheCreepySheep 2013-03-11 14:36:09

+0

是的,看到更新。 – GojiraDeMonstah 2013-03-11 16:11:42

4

沒有爲DownloadFile過載,使以前的文件

My.Computer.Network.DownloadFile 
     (address, destinationFileName, userName, 
     password, showUI, connectionTimeout, overwrite) 

的覆蓋作爲從MSDN

  • 地址=字符串或URI。要下載的文件的路徑,包括文件名稱和主機地址 。需要。
  • destinationFileName = String。下載的 文件的文件名和路徑。需要。
  • userName = String。用戶名進行身份驗證。缺省值是一個空的 字符串,「」。
  • password =要認證的String.Password。默認值爲空字符串,「 」。
  • showUI = Boolean.Specifications是否顯示 操作的進度。默認值是False。
  • connectionTimeout = Int32。超時間隔,以毫秒爲單位。默認 是100秒。
  • overwrite = Boolean。指定是否覆蓋現有文件。 默認爲False。

這樣,就可以用這種方法改變你的代碼

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    My.Computer.Network.DownloadFile _ 
    (address := "http://www.randomurl.com/randomfile.txt", _ 
    destinationFileName := Path.Combine(Environment.GetFolderPath(_ 
    Environment.SpecialFolder.ApplicationData), _ 
    "test/randomfile.txt"), _ 
    userName := string.Empty, password := string.Empty, _ 
    showUI := False, connectionTimeout := 100000, _ 
    overwrite := True) 
End Sub 
+1

你很明顯是更好的答案,因爲它回答了原來的問題。 – GojiraDeMonstah 2013-03-12 13:25:36