使用 FileSystemWatcher 监视多个文件夹

发布于 2024-08-30 17:07:16 字数 57 浏览 3 评论 0原文

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

Whats the best way to monitor multiple folders (not subdirectories) using FileSystemWatcher in C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

吻泪 2024-09-06 17:07:16

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

I don't think FSW supports monitoring multiple folders, so just instantiate one per folder you want to monitor. You can point the event handlers at the same methods, though, which should end up working like I think you want.

愛上了 2024-09-06 17:07:16

最简单的方法是创建 FileSystemWatcher 的多个实例目的。

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

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

虽然有些常见的情况,例如
复制或移动文件时,不要
直接对应于一个事件,这些
事件确实会导致事件发生
提出。当您复制文件时,
系统引发 Created 事件
文件复制到的目录
但不会引发任何事件
原始目录。当您移动一个
文件时,服务器引发两个事件:
源目录中删除的事件,
随后是 Created 事件
目标目录。

例如,您创建两个实例
FileSystemWatcher 的。
FileSystemWatcher1 设置为监视
“C:\我的文档”,以及
FileSystemWatcher2 设置为监视
“C:\您的文档”。现在,如果你复制
将文件从“我的文档”复制到“您的
Documents”,创建的事件将是
由 FileSystemWatcher2 引发,但没有
引发事件的原因是
文件系统观察者1。与复制不同的是,
移动文件或目录会引发
两个事件。从前面的例子来看,
如果您从“我的
文件”到“您的文件”,
创建的事件将由
FileSystemWatcher2 和删除事件
将由 FileSystemWatcher 引发

FileSystemEventArgs

The easiest way is to create multiple instances of the FileSystemWatcher object.

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

You'll have to make sure the you handle events between the two folders correctly:

Although some common occurances, such
as copying or moving a file, do not
correspond directly to an event, these
occurances do cause events to be
raised. When you copy a file, the
system raises a Created event in the
directory to which the file was copied
but does not raise any events in the
original directory. When you move a
file, the server raises two events: a
Deleted event in the source directory,
followed by a Created event in the
target directory.

For example, you create two instances
of FileSystemWatcher.
FileSystemWatcher1 is set to watch
"C:\My Documents", and
FileSystemWatcher2 is set to watch
"C:\Your Documents". Now, if you copy
a file from "My Documents" into "Your
Documents", a Created event will be
raised by FileSystemWatcher2, but no
event is raised for
FileSystemWatcher1. Unlike copying,
moving a file or directory would raise
two events. From the previous example,
if you moved a file from "My
Documents" to "Your Documents", a
Created event would be raised by
FileSystemWatcher2 and a Deleted event
would be raised by FileSystemWatcher

Link to FileSystemEventArgs

烟沫凡尘 2024-09-06 17:07:16

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

不过,您可以尝试利用 FileSystemWatcher 包含子目录的功能来欺骗此行为。您可以创建一个 NTFS 连接点(也称为符号链接)作为您正在观看的目录的子目录。 Sysinternals 出名的 Mark Russinovich 有一个名为 Junction 的实用程序,用于简化创建和管理符号链接。

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

Out of the box, FileSystemWatcher only supports monitoring a single parent directory. To monitor multiple sibling directories, you would need to create multiple instances of FileSystemWatcher.

You can try cheating this behavior, however, by taking advantage of FileSystemWatcher's ability to include subdirectories. You can create an NTFS junction point (aka symbolic link) as a subdirectory from the directory you are watching. Mark Russinovich of Sysinternals fame has a utility called Junction to simplify creation and management of symlinks.

Note that you can only create symlinks to directories on your local machine.

无边思念无边月 2024-09-06 17:07:16

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

那么,目的是使用 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);
        }
    }
}

Although this is an old question I decided to answer, because I couldn't find a good answer anywhere.

So, the aim was to monitor multiple folders (not subdirectories) using FileSystemWatcher? Here's my suggestion:

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);
        }
    }
}
温柔戏命师 2024-09-06 17:07:16

您是否可以简单地使用 FileSystemWatcher 的多个实例,每个目录一个?

Can you simply use multiple instances of the FileSystemWatcher, one for each directory?

可爱咩 2024-09-06 17:07:16

您必须实例化 FileSystemWatcher 对象的多个实例。不过,您可以将事件绑定到相同的方法,并使用发送者对象来确定哪个 FileSystemWatcher 触发了该事件。

        var fsw1 = new FileSystemWatcher();
        var fsw2 = new FileSystemWatcher();
        FileSystemEventHandler fsw_changed = delegate(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} - {1}", (sender as FileSystemWatcher).Path, e.ChangeType);
        };
        fsw1.Changed += fsw_changed;
        fsw2.Changed += fsw_changed;

You would have to instantiate multiple instances of the FileSystemWatcher object. Though you can bind the Events to the same method and use the sender object to determine which FileSystemWatcher triggered the event.

        var fsw1 = new FileSystemWatcher();
        var fsw2 = new FileSystemWatcher();
        FileSystemEventHandler fsw_changed = delegate(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} - {1}", (sender as FileSystemWatcher).Path, e.ChangeType);
        };
        fsw1.Changed += fsw_changed;
        fsw2.Changed += fsw_changed;
会发光的星星闪亮亮i 2024-09-06 17:07:16

或者您可以在代码中传递路径,以标记监视的域的特定范围,如下所示:

多个监视器链接

希望这有帮助。

or you can pass the paths in-code, to mark a certain range of the domain watched like in this :

multiple monitor link

hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文