C# Renci.SshNet:无法上传 SFTP 根目录之外的文件 - 当前工作目录中的斜杠将转换为反斜杠



我使用以下方法将文本文件上传到SFTP服务器。当我将目标路径设置为 root ("/"( 时,文件上传没有问题。当我尝试将文件上传到根目录("/upld/"(的子目录时,没有上传任何文件,但也没有错误。

有趣的是,在调用client.ChangeDirectory后,客户端上的WorkingDirectory属性确实会正确更新,只是它"upld"。但是上传就是不起作用。

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

你的代码对我来说很好用。

问题可能是您观察到的:在组装上传文件的完整路径时,您的 SFTP 服务器(不是 C#(将斜杠转换为反斜杠,这会使 SSH.NET 库感到困惑。

请注意,SFTP 协议(与 FTP 相反(没有工作目录的概念。工作目录只是由 SSH.NET 在客户端模拟。

很有可能,您可以通过在UploadFile调用中使用绝对路径而不是使用相对路径来解决问题:

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

最新更新