简体   繁体   中英

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\u0026quot; . 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);
}

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));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM