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

Checking connection state with WinSCP .NET assembly in C#

我有一个在 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 
}

在您的代码中,您已经知道连接是否成功。无论如何,如果你出于某种原因想要明确测试,你可以检查 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指定。