I have some code that watches the file system for changes and updates a container of file representations. All works for the most part, until you rename a directory. I would expect to get a rename event for all the files and subfolders of the renamed directory since they have new paths, but I only get a single message that the parent directory has changed names. Is there an event i’ve forgotten, or a flag that needs set? Currently I’m handling the directory rename and iterating through my collection to update the files to the new name, but I feel like there should be something in place to receive a notification for each file instead.
My setup:
FileSystemWatcher watcher = new FileSystemWatcher(item.Path);
watcher.EnableRaisingEvents = true;
watcher.Created += new System.IO.FileSystemEventHandler(OnMediaCreated);
watcher.Deleted += new System.IO.FileSystemEventHandler(OnMediaDeleted);
watcher.Changed += new System.IO.FileSystemEventHandler(OnMediaChanged);
watcher.Renamed += new System.IO.RenamedEventHandler(OnMediaRenamed);
I don’t think one usually consider the contained files to be changing if the container changes it’s name. Which would be why you don’t get an event for the contained files.
May I suggest that you create a double-linked tree-representation of the directory structure, so that each file and directory knows of the container it is in. Then make a ToString() override in the file representation that traverses your tree to the root to build the display-string.
When you get your directory rename event you can find the directory in your representation and trigger an update for each of the files leafing out from this branch.
That way you won’t have to loop through things, but rather use recursion, if that seems more elegant to you.
Also, note that FileSystemWatcher has a buffer overflow issue you might wanna check out so you don’t loose events.