Post a reply

Before posting, please read how to report bug or request support effectively.

Bug reports without an attached log file are usually useless.

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

martin

Re: Connection timed out

Thanks for sharing your solution.
Tony Smith

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