Disposing client without disconnecting

Oct 13, 2016 at 5:34 PM
What is the best practice between these two examples? Does it make sense to put the Disconnect() in a finally block to ensure it is always called or is it acceptable to simply allow dispose to close the channel? I haven't found many examples on the best way to use this library. What is the correct way to handle exceptions after connecting to the SFTP server?
  • When the client is disposed it sends a command to close the channel and hides some internal exceptions.
  • Disconnect() closes the channel and then sends a command to disconnect.
Example 1:
using (var client= new SftpClient(connectionInfo))
{
    client.Connect();
    // There is a possibility that an exception could occur here.
    client.ListDirectory("");
    client.Disconnect();
}
Example 2:
using (var client= new SftpClient(connectionInfo))
{
    try
    {
        client.Connect();
        // There is a possibility that an exception could occur here.
        client.ListDirectory("");
    }
    catch(Exception exception)
    {
        // handle the exception
    }
    finally
    {
        client.Disconnect();
    }
}