如何在VB.NET中使用WinSCP检查与SFTP服务器的连接是否成功

时间:2016-04-23 10:19:30

标签: vb.net connection sftp winscp winscp-net

我已经使用VB.NET中的WinSCP将SFTP文件发送到另一台服务器。

我想看看连接是否成功。

我还需要事先知道文件是否已存在于目录中。

1 个答案:

答案 0 :(得分:1)

你可以做几件事。您可以创建会话日志,告诉您(详细信息)文件传输过程中发生的情况。您还可以在mySession.Open(mySessionOptions)周围放置一个try-catch块来捕获错误。

最后,使用mySession.FileExists(remotepath)检查文件是否已在服务器上。

Dim mySessionOptions As New SessionOptions
With mySessionOptions
    .Protocol = Protocol.Sftp
    .HostName = "999.999.999.999"
    .UserName = "login"
    .Password = "mypassword"
    .SshHostKeyFingerprint = "ssh-dss 1024 99:87:99:4d:99:a3:99:b9:99:15:99:f2:99:87:88:b2"
End With

Using mySession As Session = New Session
    ' Will continuously report progress of synchronization
    AddHandler mySession.FileTransferred, AddressOf FileTransferred

    ' Connect
    mySession.SessionLogPath = "C:\Users\yourName\yourFolder\Sessionlog.log"

    'Use Try-Catch to check for error in connection
    Try
         mySession.Open(mySessionOptions)
    Catch ex As Exception
         MessageBox.show(ex.Message)
         mySession.Close()
         Exit Sub
    End Try

    'Check to see if file exist already on server
    If mySession.FileExists(remotePath) Then
           MessageBox.Show("File Exists on Server")
           mySession.Close()
           Exit Sub
    End If

    mySession.PutFiles("C:\Users\yourName\yourFolder\yourfile.dat", remotePath)

    mySession.Close()

End Using

请记住检查您创建的日志,以确切了解发生的情况。