Search code examples
c#.netsftpssh.net

Counting SFTP files matching certain criteria using SSH.NET


I have a working program that deletes log files from a remote server (based on a certain pattern). Now when I want to get the count of files that match my criteria I am getting problems. It turns I cannot directly get the count from the SftpFile file object. I can only get the count of the files after setting a breakpoint.

I am able to delete the files using :

private void ListDirectory(SftpClient client, String dirName)
{
    var fileext = ".log";
    var fileextension = fileext.ToString();

    foreach (SftpFile file in client.ListDirectory(dirName))
    {
        var logFilePath = file.FullName;
        var fileCount = client.ListDirectory(dirName).GetEnumerator();

        if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
        {
            Console.WriteLine(file.FullName);
            client.Delete(logFilePath);
            Console.ReadKey();
        }
    }
}

And when I do set a breakpoint I can get the count from a nested object of this line:

var fileCount = client.ListDirectory(dirName).GetEnumerator();

I have a snapshot of the debug:

enter image description here

Now I need a way to directly access the count of files for my pattern i.e this line:

if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))

When I try to apply some Linq as below:

 var fileCount = client.ListDirectory(dirName).Where((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension)).Count();

I get further exception saying

Cannot convert from 'bool' to 'system.func


Solution

  • The syntax you have in Where method argument is not a valid lambda function, you miss the parameter list. It should be:

    .Where(file => (file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
    

    Also, do not call ListDirectory repeatedly, let alone in every iteration.

    var files = client.ListDirectory(dirName);
    files =
        files.Where(
            file => (file.Name != ".") && (file.Name != "..") &&
            file.Name.EndsWith(fileextension));
    
    int count = files.Count();
    foreach (SftpFile file in files)
    {
        // ...
    }