[英]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
因此,您可以通過這種方式更改代碼
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.