FileSystemWatcher Files in a Subdirectory

I am trying to get a notification if a file is created, copied or moved to the directory that I am viewing. I want only to receive notifications about files, but not about directories.

Here is 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;

The problem is that if I move the directory containing the file in it, I do not receive any events for this file.

How can I get it to notify me of all added files (no matter how) to the watched directory or its subdirectories?

Incase I haven’t explained enough ... I have WatchedDirectory and Directory1. Directory1 contains Hello.txt. If I translate Directory1 to WatchedDirectory, I want to receive a notification for Hello.txt.

The EDIT: . I should note that my OS is Windows 8. And I get a notification about copy / paste events, but I do not move events (drag and drop to a folder).

+5
source share
3 answers

Perhaps this workaround may come in handy (but I will be careful about performance, as it is related to 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);
        }
    }
}
+3
source

Add some more filters to NotifyFilters. At the moment, you are only observing changes in file names. This, along with handlers modified and renamed, should do the job.

_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite

This seems to work only for copy / paste actions. For action cut / paste (or drag & drop), add the following filter notifications: NotifyFilters.DirectoryName.

EDIT

, . , . , , , .

, @AlexFilipovici , () ( , ). FSWatcher, .

+3

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

Link: MSDN

0
source

All Articles