Question

I'm adding SSH command execution and file upload to an existing application. After comparing different free and licensed libraries, I decided to use http://code.google.com/p/ssh2-net/ because it seems to be a port of the JAVA library to C#. We already had good experiences with the JAVA version...

Uploading a file is not very succeeding... Can anyone help? This is my code which is the combination of some bit of samples I found

Connection conn = StartConnection();    
// --> conn checked and is open!

Session session = conn.openSession();
session.execCommand("sudo mount -o remount,rw /");
// --> no error

SFTPv3Client client = new SFTPv3Client(conn);
// --> this throws error "Cannot access a closed Stream."

SFTPv3FileHandle handle = client.createFile("/tmp/" + sshSource.Name);

using (StreamReader sr = new StreamReader(sshSource.FullName)) 
{
    char[] buffer = new char[1024];
    int offset = 0;

    while (sr.Peek() >= 0)
    {
        int i = sr.Read(buffer, offset, buffer.Length);

        byte[] bytes = new byte[1024];
        for (int j = 0; j < 1024; j++)
            bytes[j] = (byte) buffer[j];

        client.write(handle, offset, bytes, 0, i);
        offset += i;
    }
}

As mentioned in the comment, there is already an error on the line where the client is defined SFTPv3Client client = new SFTPv3Client(conn);

Thanks a lot in advance for any help, Frank

Was it helpful?

Solution

switched to SharpSsh and seems to be a better (easier) solution for C#

http://www.tamirgal.com/blog/page/SharpSSH.aspx

SshTransferProtocolBase tx = new Scp(_hostname, _username, _password);
SshExec exec = new SshExec(_hostname, _username, _password);

tx.Connect();
exec.Connect();

exec.RunCommand("sudo mount -o remount,rw /");
exec.RunCommand("sudo rm /tmp/" + Path.GetFileName(sshTarget));
tx.Put(sshSource.FullName, "/tmp/" + Path.GetFileName(sshTarget));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top