使用C#中的WinSCP .NET程序集检查连接状态

时间:2017-09-20 08:53:46

标签: c# .net sftp winscp winscp-net

我有一种方法可以在C#中重试WinSCP的连接。

我如何知道我的连接状态是打开还是关闭?在WinSCP .Net中是否有这方法?

using (Session session = new Session())
{
    try
    {
        session.Open(sessionOptions);
    }
    catch(Exception ex)
    {
        //I want to reconnect here if my connection
        //is timed out
        //I want to reconnect here 3 times
    }


    // Upload file
    session.PutFiles(@"C:\Test\files.dat", "var/test/files.dat");

    // I want also to reconnect here if my upload failed
    // reconnect to the server then upload the files that 
    // did not upload because of the connection errors 
}

1 个答案:

答案 0 :(得分:1)

在您的代码中,您已经知道,如果连接成功与否。无论如何,如果您想出于某种原因明确测试,可以查看Session.Opened

using (Session session = new Session())
{
    int attempts = 3;
    do
    {
        try
        {
            session.Open(sessionOptions);
        }
        catch (Exception e)
        {
            Console.WriteLine("Failed to connect - {0}", e);

            if (attempts == 0)
            {
                // give up
                throw;
            }
        }
        attempts--;
    }
    while (!session.Opened);

    Console.WriteLine("Connected");
}

如果在传输过程中连接丢失,文件传输操作(如Session.PutFiles)会自动重新连接。

Session.ReconnectTime指定保持重新连接的时间。