C# FileSystemWatcher特定事件
我有一个程序,可以监视目录(stage)中通过另一个服务传入的任何文件(通常是FTP文件)。我有一个方法来监视目录和一个事件,当文件进入时会触发该事件,但当文件移动到存档时也会触发相同的方法。 我希望我的监视方法仅在文件出现并触发事件时进行监视,而不是在文件移出同一目录时进行监视C# FileSystemWatcher特定事件,c#,.net,filesystemwatcher,C#,.net,Filesystemwatcher,我有一个程序,可以监视目录(stage)中通过另一个服务传入的任何文件(通常是FTP文件)。我有一个方法来监视目录和一个事件,当文件进入时会触发该事件,但当文件移动到存档时也会触发相同的方法。 我希望我的监视方法仅在文件出现并触发事件时进行监视,而不是在文件移出同一目录时进行监视 private void MonitorDirectory(string path) { _watcher = new FileSystemWatcher();
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
}
该事件在文件进入时触发一次,在文件移动时触发一次。我将其过滤为仅在文件进入时触发,而不是在文件移动时触发。尝试使用
创建的
而不是更改的
因为Changed
观察路径中文件的所有更改(包括创建、删除)
在更改指定路径中的文件或目录时发生
我最初建议您订阅
Created
事件,而不是Changed
事件,但您已经提到,在创建文件时,似乎不会触发该事件
我隐约记得自己也遇到过类似的问题,最后订阅了Changed
事件,然后在事件参数中检查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
}
}
进一步信息:您可以检查文件是否已移动,并且在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
}
}
一旦创建了事件,当我将文件复制到后台时,仅当创建的文件甚至没有触发事件时才会触发事件。。我们不会在目录上创建文件,这些文件从另一个服务推送,一旦处理完毕,就会移动到存档directory@alangilbi
移动
是一种更改(重命名),而不是创建,除非您“移动”到其他位置disk@alangilbi如果事件处理程序花费的时间太长,FSW将删除事件。您应该将任何繁重的处理卸载到任务中,并为我之前创建的FSWYeah设置一个大缓冲区,但是,当文件被FTP发送到我的阶段时,它甚至不会捕获任何事件。我认为在阶段中创建的文件与通过服务或FTP发送到我的阶段之间有区别。NotifyFilter是否有可以更改的内容?当我将文件复制到我的阶段时,它甚至不会触发事件。。我们不会在目录上创建文件,它们是从另一个服务推送的,一旦处理完毕,它们就会被移动到存档目录。当我将文件复制到后台时,它甚至不会触发事件。。我们不会在目录上创建文件,这些文件从另一个服务推送,一旦处理完毕,就会移动到存档directory@alangilbi当创建的
事件没有按预期触发时,我使用了以前使用的方法更新了我的答案
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
}
}