che*_*man 95 c# io filesystemwatcher copy winforms
我正在使用Windows窗体应用程序来监视目录并将其中的文件移动到另一个目录.
目前它会将文件复制到另一个目录,但是当添加另一个文件时,它将以没有错误消息结束.有时它会在结束第三个文件之前复制两个文件.
这是因为我使用的是Windows窗体应用程序而不是控制台应用程序吗?有没有办法可以阻止程序结束并继续观看目录?
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();
}
Run Code Online (Sandbox Code Playgroud)
che*_*man 135
问题是通知过滤器.该程序试图打开一个仍在复制的文件.我删除了除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;
}
Run Code Online (Sandbox Code Playgroud)
小智 24
原因可能是观察者被声明为方法的局部变量,并且在方法完成时被垃圾收集.您应该将其声明为类成员.请尝试以下方法:
FileSystemWatcher watcher;
private void watch()
{
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.
}
Run Code Online (Sandbox Code Playgroud)