Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinSCP .NET assembly: How to download directories

I wrote a application in C# that uses System.IO.GetDirectoires() and System.IO.GetFiles()

I now have to convert that to use SFTP. I have experience with PutFiles and GetFiles of WinSCP .NET assembly, but I cannot figure out how to get a list of directories. There is a GetFiles in the winscp.exe that I can use for the files but there is no way to get the directories as far as I can tell. Does anyone have a way to do this or is there a library that is easier to work with.

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);
}
like image 938
user3753693 Avatar asked Dec 04 '15 17:12

user3753693


2 Answers

The Session.GetFiles of WinSCP .NET assembly downloads both files and subfolders.


Actually, you have to explicitly specify, when you do not want to download them.

See How do I transfer (or synchronize) directory non-recursively?


If you want to list subfolders in a remote directory, use the Session.EnumerateRemoteFiles with EnumerationOptions.MatchDirectories and filter the result set to the entries with the RemoteFileInfo.IsDirectory:

IEnumerable<RemoteFileInfo> directories =
    session.EnumerateRemoteFiles(path, null, EnumerationOptions.MatchDirectories).
        Where(file => file.IsDirectory);

But again, you do not need to do this to download the directories, the Session.GetFiles does it for you.

like image 90
Martin Prikryl Avatar answered Nov 19 '22 06:11

Martin Prikryl


Try something like that

  // Connect
  session.Open(sessionOptions);

  RemoteDirectoryInfo directory = 

  session.ListDirectory("/");

  foreach (RemoteFileInfo fileInfo in directory.Files)
  {
         Console.WriteLine("{0} with size {1}, permissions {2} and last modification at {3}", fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions, fileInfo.LastWriteTime);
  }

Also try

string dumpCommand = "ls";
session.ExecuteCommand(dumpCommand)
like image 35
skalinkin Avatar answered Nov 19 '22 04:11

skalinkin