SSH.NET SftpClient:复制/复制SftpFile

问题描述:

有没有办法在复制/粘贴等复制其他目录中的文件。 .MoveTo()方法只移动SftpFile,我试过WriteAllBytes()方法使用SftpFile.Attribues.GetBytes(),但它总是写入一个损坏的文件。SSH.NET SftpClient:复制/复制SftpFile

谢谢

您几乎无法直接复制文件。有关详细信息,为什么,请参阅:
In an SFTP session is it possible to copy one remote file to another location on same remote SFTP server?


所以,你必须下载并重新上传文件。

做到这一点(不创建一个临时的本地文件)最简单的方法是:

SftpClient client = new SftpClient("exampl.com", "username", "password"); 
client.Connect(); 

using (Stream sourceStream = client.OpenRead("/source/path/file.dat")) 
using (Stream destStream = client.Create("/dest/path/file.dat")) 
{ 
    sourceStream.CopyTo(destStream); 
} 

这里是如何复制远程文件到新的一个:

using (var sftp = new SftpClient(host, username, password)) 
{ 
    client.Connect(); 

    using (Stream sourceStream = sftp.OpenRead(remoteFile)) 
    { 
    sftp.UploadFile(sourceStream, remoteFileNew)); 
    } 
} 
+0

什么是你的答案显示在我现有的答案的顶部? –