Search code examples
c#sftpfile-renamewinscpwinscp-net

Remove or move only selected files with SFTP protocol using WinSCP .NET assembly


I'm trying to develop a simple SFTP file transferring project with following operations

  1. Upload
  2. Download
  3. Move files within the remote server
  4. Remove files

While uploading in session.PutFiles() we have a property called transferOptions.FileMask to filter the files.

But I didn't see anything of that kind in session.MoveFile() and in session.RemoveFiles()

My question is what should I do if I need to move/remove only selected files?


Solution

  • The Session.RemoveFiles accepts a file mask.

    So you can do:

    session.RemoveFiles("/home/user/*.txt");
    

    It's the same as with the Session.PutFiles. The TransferOptions.FileMask is actually intended for advanced selections, like when you want to select files recursively, or when you want to exclude certain types of files.

    session.PutFiles(@"c:\toupload\*.txt", "/home/user/");
    

    With the TransferOption.FileMask, WinSCP would upload all matching files recursively. While with a simple file mask as the argument to the .PutFiles, it's not recursive.


    The Session.MoveFile actually supports the file mask in its first argument too, though it's an undocumented feature.

    A proper way would be to list remote directory, select desired files and call the Session.MoveFile for each.

    See Listing files matching wildcard. It's a PowerShell example, but mapping it to C# should be easy.