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

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

问题描述

我使用的是Windows窗体应用程序监控目录,移动文件中下降到另一个目录。

目前,它会将文件复制到另一个目录,但增加了一个文件,它只是没有错误消息结束。有时它的第三个结束前两个文件拷贝。

这是因为我使用的是Windows窗体应用程序,而不是一个控制台应用程序?有没有一种方法,我可以从结束停止程序,并保持观望的目录?

 私人无效手表()
{
  FileSystemWatcher的守望者=新FileSystemWatcher的();
  watcher.Path =路径;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter =*;
  watcher.Changed + =新FileSystemEventHandler(调用onChanged);
  watcher.EnableRaisingEvents = TRUE;
}私人无效调用onChanged(对象源,FileSystemEventArgs E)
{
  //复制文件到另一个目录。
}


解决方案

的问题是通知过滤器。该计划试图打开仍在复制文件。我删除了所有的通知过滤器除了LastWrite。

 私人无效手表()
{
  FileSystemWatcher的守望者=新FileSystemWatcher的();
  watcher.Path =路径;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter =*;
  watcher.Changed + =新FileSystemEventHandler(调用onChanged);
  watcher.EnableRaisingEvents = TRUE;
}

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.

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()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

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

解决方案

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天全站免登陆