【问题标题】:How to list directories using SSH.NET?如何使用 SSH.NET 列出目录?
【发布时间】:2018-05-23 20:20:56
【问题描述】:

我需要列出我的 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);
    }
}

【问题讨论】:

  • files.Select(f => f.Name).Where(x=> x.IsDirectory) 并且可能忽略“。”和“..”

标签: c# ssh ssh.net


【解决方案1】:

在类 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&lt;T&gt;,因为如果ListDirectory 要返回一个惰性求值的枚举,那么using() 块将在操作完成之前使父SftpClient 对象无效 - 相同你永远不会从using( DbContext ) 中返回IQueryable&lt;T&gt; 的原因)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多