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);
}
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With