如何从vb.net中的FTP服务器(LAN / IP地址)下载文件

时间:2017-11-02 23:31:32

标签: vb.net ftp

在每个我需要帮助的机构中,我从主机上添加了我的excel文件;但文件是EMPTY(0k)。我使用了这个简单的代码:

'on event click
Dim address As String = "ftp://172.xx.xx.x/C:/aero_mes/A_0101.xls"
Dim locadress As String = "C:/bdcrq/A_0101.xls"
Try
    download = New WebClient
    download.DownloadFileAsync(New Uri(address), locadress)
Catch ex As Exception
    MsgBox(ex.Message)
End Try

2 个答案:

答案 0 :(得分:1)

您正在使用异步方法。您需要有一个事件处理程序来知道它何时完成。使用此示例并根据您的需要进行更改,因为它基于您的代码。

 Sub DownloadFile()
            Dim address As String = "http://ftp.redhat.com/redhat/cdk/3.1.1/en/source/MD5SUM"
            Dim locadress As String = "C:\dump\MD5SUM"
            Dim download As WebClient
            Try
                download = New WebClient
                download.DownloadFileAsync(New Uri(address), locadress)
                AddHandler download.DownloadFileCompleted, AddressOf FinishDownload
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Sub


        Sub FinishDownload(sender As Object, e As AsyncCompletedEventArgs)
            Try

                '  If the request was not canceled and did not throw
                '  an exception, display the resource.
                If e.Cancelled = False AndAlso e.Error Is Nothing Then

                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Sub

答案 1 :(得分:0)

我喜欢Chillzy的回答,但另一种方法是使用DownloadFile()而不是DownloadFileAsync()

DownloadFileAsync将在后台开始下载,你必须做一些类似Chillzy建议的事情,以便在完成后得到通知。

下载文件不会返回,直到它完成,因此它更容易。

DownloadFile的缺点是,如果您在WinForms UI的前台线程上,则在下载文件时不能处理任何UI事件。如果花费的时间太长,你就会感到害怕......#34;没有回应"白屏。

Chillzy的另一个优势是你还可以添加一个DownloadProgressChanged事件处理程序来获取进度并更新ProgressBar。