Search code examples
c#.netsftpssh.net

Retry SFTP if it fails?


I am using SSH.NET to upload. But I want to retry to sftp the file if the process fails. I have this code but I don't think this is the best way to handle a retry. What would be the best way to go about handling this?

var exceptions = new List<Exception>();
int retryCount = 3;

for (int retry = 0; retry < retryCount; retry++)
{
    try
    {
        var filePath = Path.Combine(path, fileName);

        var client = new SftpClient("ftp.site.com", 22, "userName", "password");

        client.Connect();

        if (client.IsConnected)
        {
            var fileStream = new FileStream(filePath, FileMode.Open);
            if (fileStream != null)
            {
                client.UploadFile(fileStream, "/fileshare/" + fileName, null);

                client.Disconnect();
                client.Dispose();
            }

        }
    }
    catch (Exception ex)
    {
        exceptions.Add(ex);
        System.Threading.Thread.Sleep(10000);
    }

    if (exceptions.Count == 3)
    {
        throw exceptions[0];
    }
}

Solution

  • The recommended approach for retries is transient-fault-handling library Polly.

    var retryPolicy = Policy
      .Handle<Exception>()
      .WaitAndRetry(3, retryAttempt => 
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) 
      );
    
    retryPolicy.Execute(() => {
        using (var client = new SftpClient("ftp.site.com", 22, "userName", "password")) 
        {
            /* file uploading .. */
        }
    });