SSH.NET SftpClient: Copy / Duplicate SftpFile

4.1k Views Asked by At

Is there a way to copy a file in an other directory like a copy/paste. .MoveTo() method move only the SftpFile and I tried WriteAllBytes() method using SftpFile.Attribues.GetBytes(), but it writes always a corrupted file.

Thank you

2

There are 2 best solutions below

0
On

You will hardly be able to copy the file directly. For details why, see:
In an SFTP session is it possible to copy one remote file to another location on same remote SFTP server?


So you have to download and re-upload the file.

The easiest way to do that (without creating a temporary local file) is:

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

Here is how to copy remote file to new one:

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

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