SSH.NET SFTP get directory and file listing recursively

The following does not list files in the /home directory, but rather lists files in the / (root) directory:
sftp.ChangeDirectory("home");
sftp.ListDirectory("").Select (s => s.FullName);
The following doesn't work and returns SftpPathNotFoundException:
sftp.ChangeDirectory("home");
sftp.ListDirectory("home").Select (s => s.FullName);
Following is the correct way to list files in /home directory
sftp.ChangeDirectory("/");
sftp.ListDirectory("home").Select (s => s.FullName);
get recursively

void Main()
{
    
    
    using (var client = new Renci.SshNet.SftpClient("sftp.host.com", "user", "password"))
    {
    
    
        var files = new List<String>();
        client.Connect();
        ListDirectory(client, ".", ref files);
        client.Disconnect();
        files.Dump();
    }
}
//注意:递归的时候需要过滤文件名为.或者..的文件夹否则会进去死循环
void ListDirectory(SftpClient client, String dirName, ref List<String> files)
{
    
    
    foreach (var entry in client.ListDirectory(dirName))
    {
    
    
		//跳过.或者..避免死循环
        if (entry.Name == "." || entry.Name == "..")
            continue;
        if (entry.IsDirectory)
        {
    
    
            ListDirectory(client, entry.FullName, ref files);
        }
        else
        {
    
    
            files.Add(entry.FullName);
        }
    }
}

Supongo que te gusta

Origin blog.csdn.net/weixin_43972758/article/details/118306291
Recomendado
Clasificación