Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list directories using SSH.NET?

Tags:

c#

ssh

ssh.net

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);
    }
}
like image 221
Hozuki Ferrari Avatar asked Nov 03 '25 21:11

Hozuki Ferrari


1 Answers

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 ))

like image 153
Dai Avatar answered Nov 05 '25 11:11

Dai