使用 VB.NET over FTP 上传目录及其子目录和内容

Upload directory and its sub directories and contents using VB.NET over FTP

我想制作一个 VB.NET 软件,我们可以在其中 select 文件夹并将它们添加到列表框中。这些文件夹及其内容将在特定时间上传到 FTP 站点。我的问题是将文件夹及其内容上传到 FTP 站点的代码是什么。列表框仅包含主目录位置。列表框中可能有多个目录。按钮 3 是立即上传按钮,稍后我将连接到计时器。按钮 2 用于 selecting 目录。

到目前为止我已经做到了:

Imports System.IO

Public Class SYNC

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim dialog = New FolderBrowserDialog()
        Dim dir As String
        dialog.SelectedPath = Application.StartupPath
        If DialogResult.OK = dialog.ShowDialog() Then
            dir = dialog.SelectedPath
            ListBox1.Items.Add(Path.GetFileName(dir))
        End If

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    End Sub

End Class

您需要使用 System.Net.FtpWebRequest class.

这是我在此处找到的未经本人测试的示例(已修改为使用 Using 语句): http://www.digitalcoding.com/Code-Snippets/VB/Visual-Basic-Code-Snippet-Upload-file-to-FTP-Server.html


''' <summary>
''' Methods to upload file to FTP Server
''' </summary>
''' <param name="_FileName">local source file name</param>
''' <param name="_UploadPath">Upload FTP path including Host name</param>
''' <param name="_FTPUser">FTP login username</param>
''' <param name="_FTPPass">FTP login password</param>
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
    Dim _FileInfo As New System.IO.FileInfo(_FileName)

    ' Create FtpWebRequest object from the Uri provided
    Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)

    ' Provide the WebPermission Credintials
    _FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)

    ' By default KeepAlive is true, where the control connection is not closed
    ' after a command is executed.
    _FtpWebRequest.KeepAlive = False

    ' set timeout for 20 seconds
    _FtpWebRequest.Timeout = 20000

    ' Specify the command to be executed.
    _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    ' Specify the data transfer type.
    _FtpWebRequest.UseBinary = True

    ' Notify the server about the size of the uploaded file
    _FtpWebRequest.ContentLength = _FileInfo.Length

    ' The buffer size is set to 2kb
    Dim buffLength As Integer = 2048
    Dim buff(buffLength - 1) As Byte

    ' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
    Using _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

        Try
            ' Stream to which the file to be upload is written
            Using _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
                ' Read from the file stream 2kb at a time
                Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

                ' Till Stream content ends
                Do While contentLen <> 0
                    ' Write Content from the file stream to the FTP Upload Stream
                    _Stream.Write(buff, 0, contentLen)
                    contentLen = _FileStream.Read(buff, 0, buffLength)
                Loop

                ' Close the file stream and the Request Stream
                _Stream.Close()
                _Stream.Dispose()
                _FileStream.Close()
                _FileStream.Dispose()
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Using

End Sub

WinSCP .NET assembly 内置了递归传输。

使用 Session.PutFiles method 如:

' Setup session options
Dim mySessionOptions As New SessionOptions
With mySessionOptions
    .Protocol = Protocol.Ftp
    .HostName = "example.com"
    .UserName = "user"
    .Password = "mypassword"
End With

Using mySession As Session = New Session
    ' Connect
    mySession.Open(mySessionOptions)

    ' Upload files
    mySession.PutFiles("d:\foldertoupload\*", "/home/user/").Check()
End Using

看到一个full example


请注意 Session.PutFiles(以及整个程序集)具有同步接口(调用是阻塞的)。所以你需要从一个单独的线程执行代码,而不是从 GUI 线程。否则,您的界面将在传输过程中无响应。

要向用户提供进度反馈,请使用 Session.FileTransferProgress event and the FileTransferProgressEventArgs.OverallProgress property

(我是WinSCP的作者)