Filtering FileSystemWatcher OnRenamed Events

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am writing a directory sweeper progrqam that moves files matching some
filter (filterString) from one directory to another when they change (using
NotifyFilters.LastWrite and the OnChanged event). Works fine.

I also want to process files when they are renamed to something that is
matched by that same filterString. So, I add a handler for OnRenamed. The
problem is that I can get two events, one when the filename is changed from
something that matches filterString to something that does not, and one when
the filename is changed from something that does not match the filterString
to something that does.

I only want to process the file on the latter events, so, I'm going to have
to do my own filtering. Is there a standard way to filter using filterString?
Something like (making this up...)
Path.IsFilteredBy(Path.GetFileName(pathName), filterString)?

Or do I just have to do it on my own? And, if so, can someone give me a
one-liner that would do the job in all cases?

Thanks,
David
 
So far, noone has any good ideas, so here's my method:

When setting the FileSystemWatcher.Filter string, also create a
regular expression object. I am using:

// Convert the file filter to a regular expression for use later
String wRegexString = wFilter.Replace(@"\", @"\\");
wRegexString = wRegexString.Replace(@".", @"\.");
wRegexString = wRegexString.Replace(@"*", @".*");
wRegexString = wRegexString.Replace(@"?", @".");
wRegex = new Regex("^" + wRegexString + "$", RegexOptions.Compiled |
RegexOptions.IgnoreCase | RegexOptions.Singleline);


Then, in the OnRenamedEvent, do something like:

if (wRegex.IsMatch(e.name, 0)) { // Process it }

David
 
Back
Top