Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSystemWatcher event on adding a folder with subdirectories

I'm using a FileSystemWatcher to monitor a directory for new folders created. This would work just fine, except that each of these folders can have one or more subdirectories inside of them.

The problem is that when I copy the top level folder (with one or more subdirectories in it) the FileSystemWatcher only catches the addition of the top level folder and not the subdirectories.

Ex: Drag folder 'foo' with subdirectory 'bar' into directory being watched FileSystemWatcher notifies that new directory 'foo' was created, but says nothing about 'bar'

Am I missing something with the functionality of FileSystemWatcher or is there some other way around this?

like image 575
Dan Avatar asked Jul 27 '11 20:07

Dan


2 Answers

You also need to handle OnRenamed, as well as IncludeSubdirectories.

From MSDN:

Copying and moving folders

The operating system and FileSystemWatcher object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents. If you cut and paste a folder with files into a folder being watched, the FileSystemWatcher object reports only the folder as new, but not its contents because they are essentially only renamed.

To be notified that the contents of folders have been moved or copied into a watched folder, provide OnChanged and OnRenamed event handler methods...

like image 77
Austin Salonen Avatar answered Nov 02 '22 16:11

Austin Salonen


Setting IncludeSubdirectories does not work in this specific case.

Here's a sample i set up:

        static void Main(string[] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher(@"C:\Temp", "*.*");

            fsw.EnableRaisingEvents = true;

            fsw.Created += new FileSystemEventHandler(fsw_Created);
            fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
            fsw.Changed += new FileSystemEventHandler(fsw_Changed);

            fsw.IncludeSubdirectories = true;

            Console.ReadLine();
        }

        static void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was changed.", e.FullPath);
        }

        static void fsw_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("{0} was renamed.", e.FullPath);
        }

        static void fsw_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was created", e.FullPath);
        }

In this case, if i move foo that contains bar folder in it into C:\Temp, i will only be notified of C:\Temp\Foo created.

FileSystemWatcher is not sealed, if this functionality is vital, i would subclass it and extend it to check under created folders, and raise events for them as well (or something similar to this implementation).

like image 34
lysergic-acid Avatar answered Nov 02 '22 15:11

lysergic-acid