FileSystemWatcher files in subdirectory

后端 未结 3 1574
借酒劲吻你
借酒劲吻你 2021-01-04 20:40

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.

相关标签:
3条回答
  • 2021-01-04 20:52

    Add some more filters to your NotifyFilters. At the moment you're only watching for changes in file names. That, together with your Changed and Renamed handlers should do the job.

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

    This seems to be working only for copy/paste actions. For cut/paste actions (or drag&drop), add the following notify filter too: NotifyFilters.DirectoryName.

    EDIT

    I've played around with it a bit more and indeed only one notification for the top level folder comes in. Makes sense, if you come to think of it. Since the change type is created then you know for sure that all files and folders inside it are new and you can process them.

    So, @AlexFilipovici's approach is the only viable one, although I'd enqueue the result (folder) and process it on a worker thread (or task, whatever). You don't want to spend too much time inside a FSWatcher event handler, especially if files are coming in at a high rate.

    0 讨论(0)
  • 2021-01-04 20:57

    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.

    Reference: MSDN

    0 讨论(0)
  • 2021-01-04 21:00

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题