Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a file in sftp using renci library?

I am attempting to move file, yet nothing happens and no exceptions are reported.

    public static void MoveFiles(string source, string destination, LoginInfo loginInfo)
    {
        using (SftpClient sftp = new SftpClient(loginInfo.Uri, loginInfo.Port, loginInfo.User, loginInfo.Password))
        {
            foreach (SftpFile file in sftp.ListDirectory(source))
            {
                file.MoveTo(destination + file.Name);
            }
        }
    }

The debugger simply steps out of the foreach:

enter image description here

What am I doing wrong?

I am using the following dependencies:

using Renci.SshNet;
using Renci.SshNet.Sftp;
like image 562
Alex Gordon Avatar asked Nov 08 '25 10:11

Alex Gordon


1 Answers

You need to connect the client to the server first using

sftp.Connect();

Source

And you should also wrap it in a try-catch in case of any errors.

public static void MoveFiles(string source, string destination, LoginInfo loginInfo) {
    try {
        using (SftpClient sftp = new SftpClient(loginInfo.Uri, loginInfo.Port, loginInfo.User, loginInfo.Password)) {
            sftp.Connect();
            var files = sftp.ListDirectory(source)
            foreach (SftpFile file in files) {
                file.MoveTo(destination + file.Name);
            }
        }
    } catch(Exception ex) {
        //...handle
    }
}
like image 101
Nkosi Avatar answered Nov 09 '25 23:11

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!