by1455的自留地

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一个子程序是有关从FTP服务器上下载文件的。

Sub getFileFromFTP(ByVal localFile As String, ByVal remoteFile As String, ByVal host As String, ByVal username As String, ByVal password As String)
        Dim URI As String = host & remoteFile
        Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)

        ftp.Credentials = New System.Net.NetworkCredential(username, password)

        ftp.KeepAlive = False
        'we want a binary transfer, not textual data
        ftp.UseBinary = False

        'Define the action required (in this case, download a file)
        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
                'loop to read & write to file
                Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
                    Dim buffer(2047) As Byte
                    Dim read As Integer = 0
                    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

    End Sub

posted on 2008-02-29 18:13  by1455  阅读(5093)  评论(0编辑  收藏  举报