I need to list directories on my Ubuntu machine.
I did it with files, but I can't find similar solution for directories.
public IEnumerable<string> GetFiles(string path)
{
using (var sftpClient = new SftpClient(_host, _port, _username, _password))
{
sftpClient.Connect();
var files = sftpClient.ListDirectory(path);
return files.Select(f => f.Name);
}
}
On Unix-like OSes, including Linux, directories are files - so your ListDirectory result will return "files" (in the traditional sense) and directories combined. You can filter those out by checking IsDirectory:
public List<String> GetFiles(string path)
{
using (SftpClient client = new SftpClient( _host, _port, _username, _password ) )
{
client.Connect();
return client
.ListDirectory( path )
.Where( f => !f.IsDirectory )
.Select( f => f.Name )
.ToList();
}
}
public List<String> GetDirectories(string path)
{
using (SftpClient client = new SftpClient( _host, _port, _username, _password ) )
{
client.Connect();
return client
.ListDirectory( path )
.Where( f => f.IsDirectory )
.Select( f => f.Name )
.ToList();
}
}
(I changed the return type to a concrete List<T> because if ListDirectory were to return a lazily-evaluated enumerable then the using() block would invalidate the parent SftpClient object before the operation had completed - the same reason you never return an IQueryable<T> from within a using( DbContext ))
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