Compare filename to a mask

I have a FileInfo object. I need to compare the FullName property to a mask like "*.jpg" or "warcraft.*" or " rant.bmp" to see if it matches. How can I do this

Thanks



Answer this question

Compare filename to a mask

  • Ekta

    Hi Haris,

    Have i reached u



  • hadjici2

    I need to compare the filename against any legitimate filename mask, the ones used by windows including * and . Not just the ones listed.
  • Ather.

    These functions work to match a filename to a wildcard pattern/mask/filter

        private bool FilenameMatchesFilter(string filename, string filter)
        {
          Match theMatch = Regex.Match(filename, WildcardToRegex(filter), RegexOptions.Compiled | RegexOptions.IgnoreCase);
          return (theMatch.Value == filename);
        }
    
        private String WildcardToRegex(String wildcard)
        {
          if (wildcard == null) return null;
          StringBuilder buffer = new StringBuilder();
          char[] chars = wildcard.ToCharArray();
          for (int index = 0; index < chars.Length; ++index)
          {
            if (chars[index] == '*')
              buffer.Append(".*");
            else if (chars[index] == ' ')
              buffer.Append(". ");          
            else if ("+()^$.{}[]|\\".IndexOf(chars[index]) != -1)
              buffer.Append('\\').Append(chars[index]); // prefix all metacharacters with backslash
            else
              buffer.Append(chars[index]);
          }
          return buffer.ToString().ToLower();
        } 
    
    

  • Juan Carlos Ruiz Pacheco

    Hi ,

    Do you need to just compare against the 3 mentioned above

    or any jpg file and any file having name as warcraft(what ever the extension may be) and (is it rant.bmp or rant.bmp) any bmp or only the bmp file u have mentioned

    Anyways, since fileinfo.FullName is a string object , it has so many functions like "Equals","Compare","Contains","Endswith" and "Startswith".Using these functions u can compare any filename with any extension.

    Hope u can do it now.If not , revert back with ur queries.

    Cheers,

    Ch.T.Gopi Kumar.



  • PhilippCH

    Hi Joel,

    the method GetFiles in the class System.IO.Directory gives you the possibility to specify a search pattern.

    If you already have a file list and cannot search through a directory, you'll need to check the names with regular expressions.

    --
    Regards,
    Daniel Kuppitz


  • Compare filename to a mask