【发布时间】:2019-03-25 17:27:01
【问题描述】:
我需要在我将使用FileSystemWatcher 的文件夹中记录文件的创建或复制/移动事件。问题是当我在文件夹中粘贴一个文件时,FileSystemWatcher 将引发一个 Created 事件。因此,如果我将10 文件一起粘贴到该文件夹中,FileSystemWatcher 将引发 10 个事件。如果同时复制粘贴在文件夹中的所有 10 个文件,我的要求是只引发一个事件。
请提出建议。以下是我在 MSDN 教程的帮助下编写的代码。
public class FileSystemWatcherUtil2
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
/* creation of a new FileSystemWatcher and set its properties */
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\TestFolder";
/*watch for internal folder changes also*/
watcher.IncludeSubdirectories = true;
/* 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;
/* event handlers */
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
/* watching started */
watcher.EnableRaisingEvents = true;
/* user should quit the program to stop watching*/
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
/* event handlers definition for changed and renamed */
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
【问题讨论】: