SerMarvz
SerMarvz

Reputation: 163

Checking connection state with WinSCP .NET assembly in C#

I have a method for retrying the connection of WinSCP in C#.

How would I know if the state of my connection is opened or closed? Are there methods for this in 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 
}

Upvotes: 2

Views: 5038

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202232

In your code, you already know, if the connection succeeded or not. Anyway, you can check Session.Opened, if you want to test explicitly for some reason.

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");
}

The file transfer operations, like the Session.PutFiles, reconnect automatically, if a connection is lost during transfer.

How long it will keep reconnecting is specified by Session.ReconnectTime.

Upvotes: 1

Related Questions