我需要在文件创建并更改两次后复制它。
除了使用3个FileSystemWachers之外,我不知道该怎么做。 第一个关于创造,两个关于改变。
有没有更简单的方法?
I need to copy a file after it's been created and changed twice.
I have no idea how to do it, except by using 3 FileSystemWachers. First one on creation and two for changing.
Is there any easier way?
最满意答案
FileSystemWatcher有几个事件可用于侦听文件系统上的不同类型的事件。 还有一个NotifyFilter属性,您可以使用它来指定应监视的事件类型。
所以你不需要使用三个不同的观察者; 一个就足够了。 您只需要某种形式的计数器来跟踪对文件进行了多少更改。 这是一个简单的例子:
Dictionary<string, int> changeCounter = new Dictionary<string, int>(); ... FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\Path\To\Some\Folder"; watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite; watcher.Created += OnCreated; watcher.Changed += OnChanged; ... private void OnCreated(object source, FileSystemEventArgs e) { changeCounter.Add(e.FullPath, 0); } private void OnChanged(object source, FileSystemEventArgs e) { if (changeCounter.ContainsKey(e.FullPath)) { changeCounter[e.FullPath]++; if (changeCounter[e.FullPath] == 2) { CopyFile(e.FullPath); } } }这只会在观察者检测到文件创建事件和单个文件的两个文件更改事件后调用CopyFile 。 您可能还想修改句柄删除,以防您担心一次创建,编辑,删除,重新创建和编辑文件 - 这会触发CopyFile即使从技术上讲,该文件只在编辑后才被编辑过一次创建。
The FileSystemWatcher has several events that you can use to listen to different types of events on the file system. There is also a NotifyFilter property which you can use to specify which event types it should monitor.
So you don't need to use three different watchers; one would suffice. You just need some form of counter to keep track of how many changes were made to the file. Here's a quick example:
Dictionary<string, int> changeCounter = new Dictionary<string, int>(); ... FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\Path\To\Some\Folder"; watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite; watcher.Created += OnCreated; watcher.Changed += OnChanged; ... private void OnCreated(object source, FileSystemEventArgs e) { changeCounter.Add(e.FullPath, 0); } private void OnChanged(object source, FileSystemEventArgs e) { if (changeCounter.ContainsKey(e.FullPath)) { changeCounter[e.FullPath]++; if (changeCounter[e.FullPath] == 2) { CopyFile(e.FullPath); } } }This would only call CopyFile after the watcher detected a file creation event and two file change events for a single file. You may also want to modify handle deletions, too, in case you are worried about files being created once, edited, deleted, recreated, and edited—this would trigger CopyFile even though, technically, the file has only been edited once after it was created.
更多推荐
发布评论