Search code examples
c#regexfilesystemwatcher

How can I replicate FileSystemWatcher Filter functionality with Regex in C#


I have a single FileSystemWatcher object for a c# project, and multiple patterns to match when events occur.

As a project requirement, I can't create multiple FileSystemObjects and use individual filter methods to match my patterns. So have to have one filter set to *.* to monitor all files, and when events are created I have to apply a Regex to process matching files per pattern in a loop. My patterns will contain * characters, same as how we pass it to Filter method.

How can I replicate the built in filter functionality with single Regex statement?

Some of the many FileSystemWatcher filter scenarios;

  • pi*.txt (These should match: piano.txt, pie.txt)
  • *.doc (Anything with the .doc extension should match)
  • 04*2013.txt (any text file and it should be any day in the month of april)
  • pi*ar*.jpg (prefix is pi, contains ar after prefix anywhere in the file name and has to be a jpg extension)
  • pre*ar*pre (any file with pre prefix, followed by ar and followed by another pre)
  • *.* (Anything is accepted)

Solution

  • Few time back I wrote something similar for my work

    public static string WildcardPatternToRegexPattern(string pattern)
    {
        return string.Format("^{0}$", Regex.Escape(pattern.Replace('/', Path.DirectorySeparatorChar)).Replace(@"\*", ".*").Replace(@"\?", "."));
    }