首页 > 解决方案 > 如果已经存在则覆盖 My.Computer.Network.DownloadFile (vb.net)

问题描述

我得到了这个代码,就像一个魅力!但是如果它已经存在,我怎样才能让它覆盖呢?谢谢!

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        Dim URL As String = "https://finncoding.com/assets/styles/app.css"
        Dim SaveFile As String = "app.css"

        With FolderBrowserDialog1
            TextBox1.Text = .SelectedPath
            My.Computer.Network.DownloadFile(URL, IO.Path.Combine(.SelectedPath, SaveFile))
        End With
    End If
End Sub

标签: vb.net

解决方案


好的,这就是我解决这个问题的方法。我转到My.Computer.Network.DownloadFile 的文档,并阅读了您正在调用的方法版本的帮助;有两个字符串的那个。它有一个备注部分,上面写着:

如果目标文件已经存在,DownloadFile 方法将不会覆盖现有文件。您可以使用 DownloadFile 方法的其他重载之一来指示它覆盖现有文件、提供用户凭据或指定特定的超时值。

所以我继续查看相同方法的其他版本的文档,我发现有一个:

DownloadFile (address As String, destinationFileName As String, userName As String, password As String, showUI As Boolean, connectionTimeout As Integer, overwrite As Boolean)

所以我想知道“我真的只需要地址,目的地文件名和覆盖,我应该为其他参数放什么?” 该文档为其他内容提供了默认值,因此这是一个很好的起点:

address String 要下载的文件的路径,包括文件名和主机地址。

destinationFileName String
File name and path of the downloaded file.

userName String
User name to authenticate. Default is an empty string, "".

password String
Password to authenticate. Default is an empty string, "".

showUI Boolean
True to display the progress of the operation; otherwise False. Default is False.

connectionTimeout Int32
Timeout interval, in milliseconds. Default is 100 seconds.

overwrite Boolean
True to overwrite existing files; otherwise False. Default is False.

因此我可以说你可以改变你的代码,所以它调用:

My.Computer.Network.DownloadFile(URL, IO.Path.Combine(.SelectedPath, SaveFile), "", "", False, 100000, True)
                                                                                                       ^^^^

最后一个 True 被覆盖。我会让您决定是否要更改任何其他内容,例如是否显示提供下载进度的 UI。希望您从中获得的最重要的东西不是作为答案的单行代码,而是关于如何更好地使用文档来帮助您更快地获得问题答案的提示,而不是在这里费力地写下一个问题并等待数小时对于几个字符解决方案


推荐阅读