如何覆盖下载的文件vb.net

时间:2013-03-10 17:20:13

标签: 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

2 个答案:

答案 0 :(得分:4)

DownloadFile存在重载,允许覆盖上一个文件

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

来自MSDN

  • address = String或Uri。要下载的文件的路径,包括文件 姓名和主持人地址。必需的。
  • destinationFileName = String。下载的文件名和路径 文件。必需的。
  • userName = String。要进行身份验证的用户名。默认为空 string,“”。
  • password = String.Password进行身份验证。默认是一个空字符串, “”。
  • showUI = Boolean。指定是否显示进度 操作。默认值为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

答案 1 :(得分: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