Question

I have the following FileSystemWatcher setup in my windows service.

    FileSystemWatcher Watcher = new FileSystemWatcher();
    Watcher.Path = watcherDir;
    Watcher.NotifyFilter = NotifyFilters.LastWrite;
    Watcher.Renamed += Watcher_Renamed;
    Watcher.Changed += Watcher_Changed;
    Watcher.Error += Watcher_Error;
    Watcher.Filter = "*.*";
    Watcher.IncludeSubdirectories = false;
    Watcher.EnableRaisingEvents = true;

I see some inconsistent behavior - it listens to changes in subdirectories too. I have logged to see what it finds it is bit odd.
I am watching C:\Temp\Folder1, and some other process creates a log file in C:\Temp\Folder1\Folder2. This FileSystemWatcher object is picking this info up -
1. e.FullPath gives the name of the subdirectory, in this case C:\Temp\Folder1\Folder2
2. Path.GetDirectoryName(e.FullPath) gives me the directory that I am actually watching for i.e. C:\Temp\Folder1.
3. The extension is empty and that is how I ignore this and this is how I ignore this case.

Any suggestions for how else I can figure out what is going on here?

Was it helpful?

Solution

The creation or deletion of a file within a directory is also counted as a change to that directory itself. That's the event that's being reported to you. Folder2, itself, is within the directory that you're monitoring.

The reported path is the path of the directory, not the file within it, and you'll notice that its your Changed handler being invoked, despite the fact that the file system operations are actually creation or deletion.

In your event handler, you could just check whether the reported path is a directory, and just return and perform no further processing in the event handler, if that's the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top