Vb.net问题下载

时间:2018-09-05 09:48:22

标签: vb.net

我该如何做一个检查,首先下载东西,然后才启动 program.exe ? 我已经尝试做这样的事情,但是当下载未完成时,它会执行文件操作,并且会引发一些错误。 我的代码:

Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
    Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
    client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
    Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If

1 个答案:

答案 0 :(得分:0)

您正在调用异步DownloadFile方法。异步方法不会阻塞调用线程。

为了避免出现此问题,您的代码必须像这样:

    Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
    Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
    Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
    Dim client As WebClient = New WebClient
    Try
        CheckExsist(saveFilePath, fileName)
        'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
        client.DownloadFile(downloadLink, saveFilePath)
        MsgBox("Download file completed. File saved in: " & saveFilePath)
        'Zip extraction stuff
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

这是CheckExsist子:

Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
    If System.IO.File.Exists(sourcePath) Then
        sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
        counter += 1
        CheckExsist(sourcePath, fileName, counter)
    End If
End Sub

我设法从官方网站下载了该软件,并将其另存为.zip。如果遇到任何问题或错误,请对最后几行进行编码,以编程方式提取.zip,如果您有其他问题,请随时提出。无论如何,vb.net上有很多关于zip提取的帖子