我需要将文件的创建或复制/移动事件记录到我将使用的文件夹中,我将使用FileSystemWatcher
。问题是,当我在文件夹中粘贴一个文件时,FileSystemWatcher
将引发一个创建事件。因此,如果我在该文件夹中共同粘贴10
文件,则FileSystemWatcher会引发10个事件。我的要求是如果同时复制文件夹中的所有10个文件,则只会引发一个事件。一次引发FileSystemWatcher的多个事件
请建议。以下是我使用MSDN教程编写的代码。
公共类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);
}
}
我认为唯一的真正答案OP的是,你不能,10个文件创建10个事件。这是一个FileSystemWatcher的,而不是一个PasteWatcher;) – Lazarus 2012-02-21 11:13:19
@Lazarus:您可以使用包装这将提高每10个内部'Created'事件OCCURENCES – sll 2012-02-21 11:27:15
没有自己的'CreatedEx'有一次,还是依靠10个内部'Created'事件存在的在彼此的超时期限内(在你的例子中是200ms)?您是否确实能够确定这10个事件是单个粘贴活动的结果,而不是批处理文件复制文件的结果? – Lazarus 2012-02-21 11:35:30