簡體   English   中英

如何覆蓋下載的文件vb.net

[英]How to overwrite downloaded file 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

DownloadFile有一個重載,它允許覆蓋先前的文件

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

從MSDN

  • 地址=字符串或Uri。 要下載的文件的路徑,包括文件名和主機地址。 需要。
  • destinationFileName =字符串。 文件名和下載文件的路徑。 需要。
  • userName =字符串。 要驗證的用戶名。 默認值為空字符串“”。
  • 密碼= String.Password進行身份驗證。 默認值為空字符串“”。
  • showUI =布爾值。指定是否顯示操作進度。 默認值為False。
  • connectionTimeout = Int32。 超時時間,以毫秒為單位。 默認值為100秒。
  • overwrite =布爾值。 指定是否覆蓋現有文件。 默認值為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
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/zh-cn/library/ez801hhe(v=VS.80).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM