如何使用 SSH.NET 列出目录?

Hoz*_*ari 4 c# ssh ssh.net

我需要列出我的 Ubuntu 机器上的目录。

我用文件做到了这一点,但我找不到类似的目录解决方案。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Dai*_*Dai 7

在类 Unix 操作系统(包括 Linux)上,目录就是文件- 因此您的ListDirectory结果将返回“文件”(传统意义上的)和目录的组合。您可以通过检查来过滤掉它们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();
    }
}
Run Code Online (Sandbox Code Playgroud)

(我将返回类型更改为具体的List<T>,因为如果ListDirectory要返回延迟计算的可枚举值,那么该块将在操作完成之前using()使父对象无效- 这与您从不从 a 中返回 an 的原因相同)SftpClientIQueryable<T>using( DbContext )