使用 FileSystemWatcher 监视目录 [英] Using FileSystemWatcher to monitor a directory

查看:28
本文介绍了使用 FileSystemWatcher 监视目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Windows 窗体应用程序来监视目录并将放入其中的文件移动到另一个目录.

I am using a Windows Forms Application to monitor a directory and move the files dropped in it to another directory.

目前它会将文件复制到另一个目录,但是当添加另一个文件时,它只会以没有错误消息的方式结束.有时它会在第三个文件结束之前复制两个文件.

At the moment it will copy the file to another directory, but when another file is added it will just end with no error message. Sometimes it does copy two files before ending on the third.

这是因为我使用的是 Windows 窗体应用程序而不是控制台应用程序吗?有什么办法可以阻止程序结束并继续观看目录吗?

Is this because I am using a Windows Form Application rather than a console app? Is there a way I can stop the program from ending and to keep watching the directory?

private void watch()
{
  this.watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += OnChanged;
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

public void Dispose()
{
  // avoiding resource leak
  watcher.Changed -= OnChanged;
  this.watcher.Dispose();
}

推荐答案

问题是通知过滤器.该程序试图打开仍在复制的文件.我删除了除 LastWrite 之外的所有通知过滤器.

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

这篇关于使用 FileSystemWatcher 监视目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆