SSH.NET "Cannot access a disposed object"
By Henri Parviainen
Problem - Cannot access a disposed object
I recently run into this error and it took me a while to grasp why it was happening although it ended up being a really simple answer.
I was trying to access a directory on SFTP server via SSH.NET library and got the following error:
Error: "Cannot access a disposed object"
The reason why this was happening was that my code where I tried to handle the directory was out of the scope of the defined sftp client connection as you can see in the code below.
string host = "mysftpserver.webdevolution.com";
string username = "mysftpserver.admin";
string password = "secretpassword";
var sftpClient = new SftpClient(host, 22, username, password);
using (var client = sftpClient)
{
client.Connect();
}
// Here comes the error since sftpClient connection is only
// usable inside the using block.
var files = sftpClient.ListDirectory("/mydir/"); // <- Error
// ... the rest of the code ...
Solution - Keep your code in scope by getting rid of the using block
So, the solution was to just get rid of the whole 'using' block.
string host = "mysftpserver.webdevolution.com";
string username = "mysftpserver.admin";
string password = "secretpassword";
var sftpClient = new SftpClient(host, 22, username, password);
sftpClient.Connect();
// Now it works!
var files = sftpClient.ListDirectory("/mydir/");
// ... the rest of the code ...
sftpCClient.Disconnect();