FileSystemWatcher: Ignore changes made by own process

Viewed 197

I want to ask if there is a possibility to ignore changes within the file system changed event made by the own process the FileSystemWatcher is running in. For example my own process creates a file in a watched directory and the FileSystemWatcher should recognize that it was created by the process or do not raise the event from the outset.

1 Answers

You can use a list of files the application operates on:

static private readonly List<string> WatcherFilesToIgnore = new List<string>();
try
{
  WatcherFilesToIgnore.Add(filePath1);
  WatcherFilesToIgnore.Add(filePath2);
  // some file operation
}
finally
{
  WatcherFilesToIgnore.Remove(filePath1);
  WatcherFilesToIgnore.Remove(filePath2);
}

Hence in the watcher event handler you write at the beginning:

if ( WatcherFilesToIgnore.Contains(e.FullPath) ) return;
// watcher process

Thus when your application acts on some files, the watcher will do nothing for the specified to ignore.

If you use multithreading, consider using some synchronization.


As mentionned by @CodeCaster there may be a lag between the application and the windows shell event raised.

A simple thing could be to add a Sleep(2000) for example but it can be hazardous.

Thus we can use a Dictionary<string, bool> to indicate that the process is terminated and let the watcher clean itself the list:

WatcherFilesToIgnore.Add(filePath1, false);
// file operation
WatcherFilesToIgnore[filePath1] = true;
if ( WatcherFilesToIgnore.Contains(e.FullPath) ) 
{
  if ( WatcherFilesToIgnore[e.FullPath] )
    WatcherFilesToIgnore.Remove(e.FullPath);
  return;
}
// watcher process

This only work if a real watcher event is raised else the file will remain in the list.

So we need to ensure that in case of nothing is done we remove the file:

WatcherFilesToIgnore.Add(filePath1, false);

if ( ProcessFile(filePath1) )
  WatcherFilesToIgnore[filePath1] = true;
else
  WatcherFilesToIgnore.Remove(e.FullPath);

The ProcessFile method (I factored like that for the explanation) do the operation needed and returns true if some change successed, else false (nothing done, exception raised, process aborted...).

Related