如何使用FTP同时下载多个文件

时间:2014-03-11 03:39:17

标签: vb.net multithreading vb.net-2010

我试图从ftp服务器同时下载多个文件,但无法这样做,

我试过了,

Const localFile As String = "C:\Documents and Settings\cr\Desktop\TE\New Folder\"
Const remoteFile As String = "/O/IE/TBML-T/FE/11/TB/"
Const host As String = "ftp://ftp4.example.com"
Const username As String = "username"
Const password As String = "password"

For i = 0 To ListBox1.SelectedItems.Count - 1

    Dim URI As String = host + remoteFile & ListBox1.SelectedItems(i)
    Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
    ftp.Credentials = New System.Net.NetworkCredential(username, password)
    ftp.KeepAlive = False
    ftp.UseBinary = True
    ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
    Using response As System.Net.FtpWebResponse = CType(ftp.GetResponse, System.Net.FtpWebResponse)
        Using responseStream As IO.Stream = response.GetResponseStream
            Dim length As Integer = response.ContentLength
            Dim bytes(length) As Byte

            'loop to read & write to file
            Using fs As New IO.FileStream(localFile & ListBox1.SelectedItems(i), IO.FileMode.Create)
                Dim buffer(2047) As Byte
                Dim read As Integer = 1
                Do
                    read = responseStream.Read(buffer, 0, buffer.Length)
                    fs.Write(buffer, 0, read)
                Loop Until read = 0 'see Note(1)
                responseStream.Close()
                fs.Flush()
                fs.Close()
            End Using
            responseStream.Close()
        End Using

        response.Close()
    End Using
Next

使用上面的代码我能够下载多个文件,但是当第一个文件的下载完成时它会下载第二个文件,等等,而不是我希望代码应该以所有选定文件开始下载的方式执行在同一时间。

我认为这可以通过多线程来完成,但我对此并不熟悉。

0 个答案:

没有答案