static void Main(string[] args)
Console.WriteLine("Create client Object");
using (SftpClient sftpClient = new SftpClient(getSftpConnection("host", "userName", 22, "filePath")))
bool isConnected = false;
while (!isConnected && attempt < maxRetries)
Console.WriteLine($"Attempt {attempt} to connect to server");
Console.WriteLine("Connected to server");
Console.WriteLine("Creating FileStream object to stream a file");
using (FileStream fs = new FileStream("filePath", FileMode.Open))
sftpClient.BufferSize = 1024;
sftpClient.UploadFile(fs, Path.GetFileName("filePath"));
Console.WriteLine($"An error occurred on attempt {attempt}: {ex.Message}");
if (attempt < maxRetries)
Console.WriteLine($"Retrying in {retryDelay / 1000} seconds...");
Thread.Sleep(retryDelay);
Console.WriteLine("Max retry attempts reached. Exiting.");
public static ConnectionInfo getSftpConnection(string host, string username, int port, string publicKeyPath)
return new ConnectionInfo(host, port, username, privateKeyObject(username, publicKeyPath));
private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath)
PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath);
PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(username, privateKeyFile);
return new AuthenticationMethod[] { privateKeyAuthenticationMethod };