这个库有一些怪癖,使得这个递归列表变得棘手,因为ChangeDirectory
and ListDirectory
不按您的预期工作。
下面的做法是not列出 /home 目录中的文件,而不是列出 /(根)目录中的文件:
sftp.ChangeDirectory("home");
sftp.ListDirectory("").Select (s => s.FullName);
下面的做法是not工作并返回 SftpPathNotFoundException:
sftp.ChangeDirectory("home");
sftp.ListDirectory("home").Select (s => s.FullName);
以下是列出/home目录下文件的正确方法
sftp.ChangeDirectory("/");
sftp.ListDirectory("home").Select (s => s.FullName);
如果你问我的话,这真是太疯狂了。设置默认目录ChangeDirectory
方法没有影响ListDirectory
方法,除非您在此方法的参数中指定文件夹。看来应该为此编写一个错误。
因此,当您编写递归函数时,您必须设置一次默认目录,然后更改ListDirectory
当您迭代文件夹时调用。该列表返回 SftpFiles 的枚举。然后可以单独检查这些IsDirectory == true
。请注意,列表还会返回.
and ..
条目(目录)。如果您想避免无限循环,则需要跳过这些。 :-)
编辑 2018 年 2 月 23 日
我正在审查我的一些旧答案,并想为上面的答案道歉并提供以下工作代码。请注意,此示例不需要ChangeDirectory
,因为它使用的是Fullname
为了ListDirectory
:
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.IsDirectory)
{
ListDirectory(client, entry.FullName, ref files);
}
else
{
files.Add(entry.FullName);
}
}
}