使用FileSystemWatcher监视多个文件夹

Bi.*_*Bi. 22 .net c# filesystemwatcher

什么是使用C#中的FileSystemWatcher监视多个文件夹(而不是子目录)的最佳方法?

Fac*_*tic 20

我不认为FSW支持监视多个文件夹,因此只需要实例化每个要监视的文件夹.但是,您可以使用相同的方法指向事件处理程序,这应该最终会像我想的那样工作.


kem*_*002 13

最简单的方法是创建FileSystemWatcher对象的多个实例.

http://www.c-sharpcorner.com/UploadFile/mokhtarb2005/FSWatcherMB12052005063103AM/FSWatcherMB.aspx

您必须确保正确处理两个文件夹之间的事件:

尽管一些常见的事件(例如复制或移动文件)并不直接对应于事件,但这些事件确实会引发事件.复制文件时,系统会在复制文件的目录中引发Created事件,但不会引发原始目录中的任何事件.移动文件时,服务器会引发两个事件:源目录中的Deleted事件,然后是目标目录中的Created事件.

例如,您创建两个FileSystemWatcher实例.FileSystemWatcher1设置为观看"C:\ My Documents",FileSystemWatcher2设置为观看"C:\ Your Documents".现在,如果将文件从"我的文档"复制到"您的文档"中,FileSystemWatcher2将引发Created事件,但不会为FileSystemWatcher1引发任何事件.与复制不同,移动文件或目录会引发两个事件.从上一个示例中,如果您将文件从"我的文档"移动到"您的文档",则FileSystemWatcher2将引发Created事件,FileSystemWatcher将引发Deleted事件.

链接到FileSystemEventArgs


Tim*_*out 6

开箱即用,FileSystemWatcher 仅支持监视单个父目录。要监视多个同级目录,您需要创建多个 FileSystemWatcher 实例。

但是,您可以尝试通过利用 FileSystemWatcher 包含子目录的能力来欺骗这种行为。您可以从您正在观看的目录中创建一个 NTFS 连接点(又名符号链接)作为子目录。Sysinternals 的 Mark Russinovich 有一个名为Junction的实用程序,可以简化符号链接的创建和管理。

请注意,您只能创建指向本地计算机上目录的符号链接。


Cio*_*ove 5

虽然这是一个我决定回答的老问题,因为我在任何地方都找不到好的答案。

那么,目的是使用 FileSystemWatcher 监视多个文件夹(而不是子目录)?这是我的建议:

using System;
using System.IO;
using System.Security.Permissions;
using System.Collections.Generic;

namespace MultiWatcher
// ConsoleApplication, which monitors TXT-files in multiple folders. 
// Inspired by:
// http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(v=vs.100).aspx

{
    public class Watchers
    {
        public static void Main()
        {
            Run();

        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Run()
        {
            string[] args = System.Environment.GetCommandLineArgs();

            // If a directory is not specified, exit program.
            if (args.Length < 2)
            {
                // Display the proper way to call the program.
                Console.WriteLine("Usage: Watcher.exe PATH [...] [PATH]";
                return;
            }
            List<string> list = new List<string>();
            for (int i = 1; i < args.Length; i++)
            {
                list.Add(args[i]);
            }
            foreach (string my_path in list)
            {
                Watch(my_path);
            }

            // Wait for the user to quit the program.
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
        private static void Watch(string watch_folder)
        {
            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = watch_folder;
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;
        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        }

        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            // Specify what is done when a file is renamed.
            Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • FileWatcher 实现了 IDisposable。如果在程序退出之前不再需要观察者(例如,如果特定的观察目录被删除),您的建议将通过包含确保调用 IDisposable.Dispose() 的模式得到改进。 (4认同)