Evan French
Evan French

Reputation: 77

C# Renci.SshNet: Unable to upload files outside of SFTP root - slashes in current working directory are converted to backslahes

I'm using the following method to upload a text file to an SFTP server. When I set the destination path to root ("/"), the file uploads without issue. When I attempt to upload the file to a sub-directory of the root ("/upld/"), no file is uploaded, but there is also no error.

Interestingly, after calling client.ChangeDirectory, the WorkingDirectory property on client does update correctly, except that it's "\upld". But the upload just doesn't work.

public void UploadSFTPFile(string sourcefile, string destinationpath)
{
    using (SftpClient client = new SftpClient(this.host, this.port, this.username, this.password))
    {
        client.Connect();
        using (FileStream fs = new FileStream(sourcefile, FileMode.Open))
        {
            client.UploadFile(fs, destinationpath + Path.GetFileName(sourcefile));
        }
    }
}

public void Caller()
{
    string localpath = "./foo.txt";
    string destinationpath = "/upld/"; // this does not upload any files
    //string destinationpath = "/"; // this uploads the file to root
    UploadSFTPFile(localpath, destinationpath);
}

Upvotes: 0

Views: 6974

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202504

Your code works just fine for me.

The problem is probably, what you have observed: that your SFTP server (not C#) converts the slashes to backslashes, what confuses SSH.NET library, when assembling the full path of the uploaded file.

Note that the SFTP protocol (contrary to the FTP) does not have a concept of a working directory. The working directory is just simulated on a client-side by SSH.NET.

It's quite probable that you can solve your problem by using absolute paths in the UploadFile call, instead of using relative paths:

public void UploadSFTPFile(string sourcefile, string destinationpath)
{
    using (SftpClient client = new SftpClient(host, port, username, password))
    {
        client.Connect();
        using (FileStream fs = new FileStream(sourcefile, FileMode.Open))
        {
            client.UploadFile(fs, destinationpath + Path.GetFileName(sourcefile));
        }
    }
}

Upvotes: 0

Related Questions