Connection timed out

Advertisement

Tony Smith
Donor
Joined:
Posts:
2
Location:
U.K.

Connection timed out

Issue: WinSCP intermittently (< 1 in 250 times) unable to connect to required FTP site. Connection failure causes fatal error; execution of C# script stops.

Requirement was for a retry a few seconds later, up to a maximum of three attempts.

Spent numerous hours on forum/website. Knew there was an answer somewhere but couldn't find worked example or sufficient details of how to approach it in C#.

Did resolve issue, so code below is for others who may be searching for similar.

// Set up session options
SessionOptions sessionOptions = new SessionOptions
 
{
    Protocol = Protocol.Sftp,
    HostName = _hostName,
    UserName = _userName,
    Password = _password,
    SshHostKeyFingerprint = _sshHostKey,
};
 
using (Session session = new Session())
{
    // Will continuously report progress of synchronization
    session.FileTransferred += FileTransferred;
 
    // Attempt to loop through opening the session three times.
    int loop = 0;
 
    while (loop < 3)
    {
        try
        {
            // Open session.  Break out of loop if successful   
            session.Open(sessionOptions);
            break;
        }
        catch (SessionRemoteException e)
        {
            //Increment the loop and wait 5 seconds.  If three failed attempts, throw an exception
            loop++;
            if (loop >= 3) throw e;
            System.Threading.Thread.Sleep(5000);
        }
        catch (Exception e)
        {
            // All other exceptions, pass e up to parent catch     
            throw e;
        }
    }
}

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
34,943
Location:
Prague, Czechia

Re: Connection timed out

Thanks for sharing your solution.

Reply with quote

Advertisement

You can post new topics in this forum