我正在使用Windows窗体应用程序监视目录,并将放置在其中的文件移动到另一个目录。
目前,它将文件复制到另一个目录,但是当添加另一个文件时,它只会以没有错误信息的结尾。有时它确实复制了两个文件,然后才在第三个文件结束。
这是因为我使用的是Windows Form Application而不是Console app?有什么办法可以阻止程序结束并继续监视目录?
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之外的所有通知过滤器。
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}