• Loading...
ComponentPro UltimateSftp

Connection settings, connection info and connection state

Language Filter: AllSend comments on this topic to ComponentPro

Set connection options

The Sftp.Config property has several useful connection options like EnableCompression, HostKeyAlgorithms, MacAlgorithms, etc. If needed, set those before connecting to a server.

// Create a new instance of the Sftp class. 
using (Sftp client = new Sftp())
{
    // Set security settings. 
    client.Config.HostKeyAlgorithms = SecureShellHostKeyAlgorithm.RSA;
    client.Config.KeyExchangeAlgorithms = SecureShellKeyExchangeAlgorithm.DiffieHellmanGroupExchangeSHA256;
    // Enable compression 
    client.Config.EnableCompression = true;

    // Connect to the server. 
    client.Connect(serverName);

    // ...
}

Get connection info

Some of the useful information about the current SSH session such as server/user name, server fingerprint, negotiated algorithms or SFTP protocol version are available when the connection is established or the user is authenticated.

// Create a new instance of the Sftp class. 
using (Sftp client = new Sftp())
{
    // Connect to the server. 
    client.Connect(serverName);

    // Get connection information 
    Console.WriteLine("Server: {0}:{1}, Host key: {2}, Host key algorithm: {3}, Server Identification: {4}",
                      client.ServerName, client.ServerPort, client.HostKey,
                      client.Connection.Cipher.HostKeyAlgorithm, client.Connection.ServerIdentification);

    // Authenticate the user 
    client.Authenticate(userName, password);

    Console.WriteLine("Logged in as: {0}", client.UserName);
}

Check connection state

To determine if a session is still alive, use GetConnectionState method. The method sends a "ping" packet to the server to ensure the connection is still up and running.

// Check session state 
using (Sftp client = new Sftp())
{
    // Connect to the server. 
    client.Connect(serverName);

    // Authenticate the user 
    client.Authenticate(userName, password);

    bool connected;
    int nativeErrorCode;
    // Get connection state. 
    client.GetConnectionState(out connected, out nativeErrorCode);

    Console.WriteLine(connected ? "Connection is still alive" : "Connection closed. Error code: " + nativeErrorCode);
}