到目前为止,我知道FileSystemWatcher可以查看一个文件夹,如果该文件夹中的任何文件被更改,则修改,.etc ...然后我们就可以处理它了。 但我不确定在我的场景中应该使用哪个过滤器和事件:观察文件夹,如果文件被添加到该文件夹,请执行XYZ ...所以在我的场景中我不关心现有文件是否已更改等等。应该忽略这些......当且仅当新文件被添加到该文件夹时才执行XYZ ...
您为此方案推荐了哪个事件和过滤器?
答案 0 :(得分:14)
设置观察者:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "Blah";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
然后实施FileCreated
委托:
private void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
答案 1 :(得分:3)
请在此处查看FileSystemWatcher的详细说明:http://www.c-sharpcorner.com/uploadfile/mokhtarb2005/fswatchermb12052005063103am/fswatchermb.aspx
如果要查找添加的文件,则必须查找已创建的文件。
您可以通过设置WatcherChangeType枚举的值来指定要监视的更改类型。可能的值如下:
此外,您可以连接在创建(添加)文件时触发的事件处理程序,并且不会实现所有其他事件,因为它们对您不感兴趣:
watcher.Created += new FileSystemEventHandler(OnChanged);
答案 2 :(得分:0)
下面带有注释的代码有望满足您的需求。
public void CallingMethod() {
using(FileSystemWatcher watcher = new FileSystemWatcher()) {
//It may be application folder or fully qualified folder location
watcher.Path = "Folder_Name";
// 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.if you want to track other types then mentioned here
watcher.Filter = "*.txt";
// Add event handlers.for monitoring newly added files
watcher.Created += OnChanged;
// 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 created with these properties below
// e.FullPath , e.ChangeType
}