How to sort result of Ftp.GetFiles call

0 votes
asked Jul 31, 2012 by Rebex KB (8,330 points)
edited Jul 31, 2012

I'm trying to get a list of files from a FTP or SFTP server. The result have to be ordered. How do you sort a result of GetFiles method of Rebex FTP? I need to show results ordered by file name.

Applies to: Rebex FTP/SSL, Rebex SFTP

1 Answer

0 votes
answered Jul 31, 2012 by Martin Vobr (12,940 points)
edited Jul 31, 2012

If you are using .NET 3.5 or newer you can use LINQ to sort this collection. Check following code:

using (Ftp ftp = new Ftp())
{
       ftp.Connect("host");
       ftp.Login("username", "password");

       FtpList items = ftp.GetList();

       IEnumerable<FtpItem> sortedItems =
             items.OrderByDescending(n => n.Name);

       foreach (FtpItem item in sortedItems)
       {
             Console.WriteLine("{0}", item.Name);
       }

       ftp.Disconnect();
}

If you cannot use LINQ try this code:

using (Ftp ftp = new Ftp())
{
       ftp.Connect("hostname");
       ftp.Login("username", "password");

       FtpList items = ftp.GetList();

       items.Sort(new FtpItemComparer(FtpItemComparerType.Name));

       foreach (FtpItem item in items)
       {
             Console.WriteLine("{0}", item.Name);
       }

       ftp.Disconnect();
}

The code for SFTP is almost the same. Just replace FtpList with SftpList, Ftp with Sftp and FtpItemComparer with SftpItemComparer.

...