如何使用FileSystemWatcher在C#中监视Windows系统中文件的更改 [英] How to monitor change in files in windows system in c# using filesystemwatcher

查看:134
本文介绍了如何使用FileSystemWatcher在C#中监视Windows系统中文件的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用filesystemwatcher类来监视文件更改,但就我而言,我在系统中不同位置上有数百万个文件,因此必须创建数百万个filetstemwatcher类实例,这会导致性能问题. br/>
请告诉我如何才能最大限度地提高性能,或者还有另一种方法可以监视c#中的所有文件.

Currently i am using filesystemwatcher class to watch the file changes But in my case i have millions of file on different- different location in the system, so i have to create millions instance of fileststemwatcher class which is causing the performance issue.

Please tell how can i maximize the performance or is there another way to monitor the all files in c#.

推荐答案

下面提供的代码将帮助您监视所有.txt文件在给定的文件夹中.它将监视给定文件夹和子文件夹中的所有.txt文件.对于您来说,如果您必须监视"C"驱动器中的所有.txt文件,则相应地提供FileSystemWatcher的路径,并将过滤器设置为"* .txt"(Filter ="* .txt";)并设置IncludeSubdirectories = true .然后,它将对所有.txt文件的更改触发方法"Action".


The below given code will help you monitor all .txt files inside a given folder. It will monitor all .txt file in the given folder and subfolders. For you , if you have to monitor all .txt files in "C" drive, then give the path for FileSystemWatcher accordingly and set the filter to "*.txt" (Filter = "*.txt";) and set IncludeSubdirectories = true. It will then fire method "Action" for the changes to any .txt files.


public static void Main(string[] arg)
{
    FileSystemWatcher watcher = new FileSystemWatcher(@"C:\testFolder")
                                    {
                                        IncludeSubdirectories = true,

                                        NotifyFilter = NotifyFilters.LastAccess |NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,

                                        Filter = "*.txt"
                                    };



    // Add event handlers.
    watcher.Changed += Action;
    watcher.Created += Action;
    watcher.Deleted += Action;
    watcher.Renamed += Action;

    // Begin watching.
    watcher.EnableRaisingEvents = true;

    Console.ReadLine();

}
public static void Action(object obj, FileSystemEventArgs fileInfo)
{
    Console.WriteLine(fileInfo.FullPath.ToString() + fileInfo.ChangeType);
}


这篇关于如何使用FileSystemWatcher在C#中监视Windows系统中文件的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆