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

时间:2018-05-23 20:20:57

标签: 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);
    }
}

1 个答案:

答案 0 :(得分:3)

在类Unix操作系统上,包括Linux,directories are files - 所以你的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();
    }
}

(我将返回类型更改为具体的List<T>,因为如果ListDirectory要返回一个延迟评估的可枚举,那么using()块将使父SftpClient个对象无效在操作完成之前 - 同样的原因,你永远不会从IQueryable<T>中返回using( DbContext )