Slava
Slava

Reputation: 6650

Filtering . (this folder) and .. (parent folder) in SFTP directory listing in C# SSH.NET

I connect to SFTP host.

That host has a folder files

enter image description here

And one file in it.

I need to get a list of names of file in that folder (files).

I tried:

using (var client = new SftpClient(FtpFolder, 22, FtpUsername, FtpPassword))
{
    client.Connect();
    client.ChangeDirectory("files");
    var files = client.ListDirectory(".").ToList();
    client.Disconnect();
}

enter image description here

But instead of 1 file I also get parent folder reference I think.

Please advice! Thanks.

Upvotes: 5

Views: 4009

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202494

In SFTP protocol, there's no way to ask server to filter files for you. Nor has SSH.NET API any function to filter the files for you locally. You have to do it on your own.

For example:

client.ChangeDirectory("files");
var files =
    client.ListDirectory(".").
        Where(file => (file.Name != ".") && (file.Name != "..")).ToList();

Changing directory has nothing to do with the question. Actually SFTP protocol does not even have a concept of "working directory". The "working directory" is only simulated locally by SSH.NET library.

So this is functionally equivalent:

var files =
    client.ListDirectory("/files").
        Where(file => (file.Name != ".") && (file.Name != "..")).ToList();

Upvotes: 4

Related Questions