Search code examples
c#filesystemwatcher

Unable to access directory from FileSystemEventArgs.FullPath, wrong directory name


I am using FileSystemWatcher to track changes from a directory. The problem is that I must keep track and make modifications to any recent created sub directories inside the one I am monitoring. As of now I am simply detecting some change using the Change event, checking if FullPath is a directory and creating a new instance of FileSystemWatcher for that sub directory.

private static void StartMonitoringDir(string dir)
        {
            var fileWatcher = new FileSystemWatcher(dir)
            {
                EnableRaisingEvents = true,
                Filter = "*.exe"
            };

            var folderWatcher = new FileSystemWatcher(dir)
            {
                EnableRaisingEvents = true
            };

            fileWatcher.Created += FileWatcherOnCreated;
            fileWatcher.Changed += FileWatcherOnChanged;
            folderWatcher.Created += FolderWatcherOnCreated;
        }

private static void FolderWatcherOnCreated(object sender, FileSystemEventArgs e)
        {
            var attr = File.GetAttributes(e.FullPath);

            if (attr != FileAttributes.Directory) return;

            StartMonitoringDir(e.FullPath);
        }

So, here is the problem. As soon as I create a directory the Changed event is raised with the "New Folder" name, so when the users rename this folder and makes a modification inside it, I get the old name of the folder, "New Folder", not the one named by the user. I have no way to know what the folder's new name is and am unable to make modifications, as I have the wrong directory name.


Solution

  • If you don't need to worry about someone leaving a "New Folder" folder laying around, I'd remove your 'FolderWatcherOnCreated` event handler and instead use the FileSystemWatcher.Renamed Event event handler.

    Something like this might do the trick for you (I've not tested the code):

    folderWatcher.Renamed += FolderWatcherOnRenamed;
    
    private static void FolderWatcherOnRenamed(object sender, RenamedEventArgs e)
    {
    
        var attr = File.GetAttributes(e.FullPath);
    
        if (attr == FileAttributes.Directory && e.OldName == "New Folder")
        {
    
            StartMonitoringDir(e.FullPath)
        }
    }