Black Dynamite
Black Dynamite

Reputation: 4147

C#: FileSystemWatcher only dispatches ChangedEvent

I am working with the FileSystemWatcher construct in C#. As par for the course, I am making my watchers only watch directories of interests. The problem I am having is that regardless of the user event (copy, create, rename) the only event I am picking up is the Changed event.

For example.

  1. Watch file "C:...\Desktop\MattsRequest"

  2. Create File "C:...\Desktop\MattsRequest\Dummy.txt"

  3. Observe that only the OnChanged handler is triggered with a FileSystemEventArg of "Changed" and the path arg is "C:...\Desktop\MattsRequest" and no mention of what file was created

My watcher code looks like so.

            watcher = new FileSystemWatcher();
            //watcher.IncludeSubdirectories = true;
            watcher.InternalBufferSize = 32768 * 2;
            //Can't use a synchro because I can't find an example of something that
            //implements ISynchroniz-whatever
            //watcher.SynchronizingObject =

            watcher.Path = filePath;

            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                    | NotifyFilters.FileName | NotifyFilters.DirectoryName
                                    | NotifyFilters.CreationTime;

            watcher.Changed += OnChanged;  //Gets triggered
            watcher.Created += OnCreated;  //Never triggered
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;  //Never triggered
            watcher.Error += WatcherOnError; //Never triggered

            // Begin watching.
            watcher.EnableRaisingEvents = true;

Below is an image of when I have created a new file in the watched directory, and the event that it fires off. It's of course of type Changed, but it doesn't tell me which file was created.

enter image description here

Any help is greatly appreciated.

Upvotes: 1

Views: 285

Answers (2)

Evk
Evk

Reputation: 101453

This might happen when you watch a directory and create a file inside subdirectory of that directory. That is because creating a file in a directory changes that directory's timestamp, and that is the event you see (change of the directory).

To fix - either watch subdirectory itself, or set watcher.IncludeSubdirectories = true; to include subdirectories.

Upvotes: 2

Black Dynamite
Black Dynamite

Reputation: 4147

Evk's answer was the correct one. I was watching the grandparent folder only, and that folder fired off an event which was missing the information. Once I added a watcher to the parent folder, the Created and other events were fired off correctly.

Upvotes: 0

Related Questions