[英]FileSystemWatcher Specific Event
我有一个程序,用于监视目录(阶段)中是否有通过其他服务进入的文件(通常是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
观察路径中文件的所有更改(包括创建,删除)
更改指定路径中的文件或目录时发生。
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Created += new FileSystemEventHandler(loadFile);
我最初建议您订阅Created
事件而不是Changed
事件,但是您已经提到创建文件时似乎未触发该事件。
我隐约记得我自己遇到过类似的问题,最终订阅了Changed
事件,然后在事件args中检查ChangeType
,如下所示:
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)
{
if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Renamed) {
// do some work
}
}
更多信息: MSDN文档
您可以检查文件是否已移动,并且在FileCreatedMethod的文件夹中不存在。
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)
{
if(System.IO.File.Exist(e.FullPath)
{
//Do some work and move the file received
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.