Search code examples
c#filesystemwatcher

FileSystemWatcher files in subdirectory


I'm trying to be notified if a file is created, copied, or moved into a directory i'm watching. I only want to be notified about the files though, not the directories.

Here's some of the code I currently have:

_watcher.NotifyFilter = NotifyFilters.FileName;
_watcher.Created += new FileSystemEventHandler(file_created);
_watcher.Changed += new FileSystemEventHandler(file_created);
_watcher.Renamed += new RenamedEventHandler(file_created);
_watcher.IncludeSubdirectories = true;
_watcher.EnableRaisingEvents = true;

Problem is, if I move a directory that contains a file in it, I get no event for that file.

How can I get it to notify me for all files added (regardless of how) to the watched directory or it's sub directories?

Incase I didn't explain good enough... I have WatchedDirectory, and Directory1. Directory1 contains Hello.txt. If I move Directory1 into WatchedDirectory, I want to be notified for Hello.txt.

EDIT: I should note my OS is Windows 8. And I do get notification for copy/paste events, but not move events (drag and drop into the folder).


Solution

  • Maybe this workaround could come in handy (but I'd be careful about performance as it involves recursion):

    private static void file_created(object sender, FileSystemEventArgs e)
    {
        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            if (Directory.Exists(e.FullPath))
            {
                foreach (string file in Directory.GetFiles(e.FullPath))
                {
                    var eventArgs = new FileSystemEventArgs(
                        WatcherChangeTypes.Created,
                        Path.GetDirectoryName(file),
                        Path.GetFileName(file));
                    file_created(sender, eventArgs);
                }
            }
            else
            {
                Console.WriteLine("{0} created.",e.FullPath);
            }
        }
    }