簡體   English   中英

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

[英]How to list directories using 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);
    }
}

在包括Linux在內的類Unix操作系統上, 目錄是文件 -因此,您的ListDirectory結果將返回“文件”(傳統意義上)和目錄組合。 您可以通過檢查IsDirectory來過濾掉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 ) IQueryable<T>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM