Author Topic: Howto filter Files with specific caracters in filenames?  (Read 602 times)

k.meyer

  • Newbie
  • *
  • Posts: 1
  • Karma: +0/-0
    • View Profile
Howto filter Files with specific caracters in filenames?
« on: December 20, 2017, 11:10:52 AM »
 :)
Hi, how can I filter a DirList with files containing certain characters?
As an example, all files with ".pdf"?
Or is there another way, so I do not download all files that are not intended for the site.

BR K.Meyer

juangcxt

  • Newbie
  • *
  • Posts: 2
  • Karma: +0/-0
    • View Profile
Re: Howto filter Files with specific caracters in filenames?
« Reply #1 on: December 20, 2017, 03:02:32 PM »
I get the remote directory list and then use a method like this to determine whether or not the file name matches my filter (e.g. "*.pdf").

                string handle = sftp.OpenDir(remoteDirectory);
                if (handle != null)
                {
                    using (SFtpDir files = sftp.ReadDir(handle))
                    {
                        if (files != null)
                        {
                            for (int counter = 0; counter < files.NumFilesAndDirs; counter++)
                            {
                                using (SFtpFile file = files.GetFileObject(counter))
                                {
                                    if (!file.IsDirectory)
                                    {
                                        if(FitsMask(file.Filename, "*.pdf")) fileList.Add(file.Filename);
                                    }
                                }
                            }
                        }
                    }


        private bool FitsMask(string fileName, string fileMask)
        {
            Regex mask = new Regex(
                '^' +
                fileMask
                    .Replace(".", "[.]")
                    .Replace("*", ".*")
                    .Replace("?", ".")
                + '$',
                RegexOptions.IgnoreCase);
            return mask.IsMatch(fileName);
        }