c# - FileSystemWatcher 特定事件
问题描述
我有一个程序可以监视通过另一个服务进入(通常是 FTP)的任何文件的目录(阶段)。我有一种监视目录的方法和一个在文件进入时触发的事件,但是当文件移动到存档时也会触发相同的方法。我希望我的监视方法仅在文件出现并触发事件时进行监视,而不是在文件移出同一目录时进行监视。
private void MonitorDirectory(string path)
{
_watcher = new FileSystemWatcher();
_watcher.Path = path;
_watcher.NotifyFilter = NotifyFilters.LastWrite;
_watcher.Changed += FileCreated;
_watcher.EnableRaisingEvents = true;
}
private void FileCreated(object sender, FileSystemEventArgs e)
{
//Do some work and move the file received
}
该事件在文件进入时触发一次,在文件被移动时触发一次。我将其过滤为仅在文件进入时触发,而不是在文件移动时触发。
解决方案
尝试使用Created
而不是Changed
.
因为Changed
观察路径中文件的所有变化(包括创建、删除)
当指定 Path 中的文件或目录发生更改时发生。
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Created += new FileSystemEventHandler(loadFile);