Search code examples
c#sshscp

SshConnectionException from SshNet in C#


From my script trying to connect to the unix server to download a file but getting below error..

Renci.SshNet.Common.SshConnectionException : Client not connected.

I can connect properly to that server from WinScp by using the same credentials.

Not sure what's going wrong here. Any idea/pointer ?

Code

using (var client = new ScpClient(Config.UnixServer, Config.UnixUsername, Config.UnixPassword))
{
    client.Connect();
    client.Upload(new FileInfo(fileUpload), fileName);
    client.Disconnect();
}

Error

Renci.SshNet.Common.SshConnectionException : Client not connected.
at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle)
at Renci.SshNet.Session.Connect()
at Renci.SshNet.BaseClient.Connect()

WinSCP Session Log


Solution

  • The session log shows that WinSCP is using the sftp protocol (WinSCP supports both scp and sftp protocols). Not all sftp servers will accept scp connections. Switch to the SftpClient class and use the UploadFile method.

    I also suspect you meant to call OpenRead() on your FileInfo instance to get a stream.

    using (var client = new SftpClient(Config.UnixServer, Config.UnixUsername, Config.UnixPassword))
    {
        client.Connect();
        client.UploadFile(new FileInfo(fileUpload).OpenRead(), fileName);
        client.Disconnect();
    }