FileSystemWatcher事件未触发
本文关键字:事件 FileSystemWatcher | 更新日期: 2023-09-27 18:04:37
我的FileSystemWatcher没有抛出任何事件。我看过这些类似的问题,似乎没有一个能回答我的问题:
*编辑:我的目标是捕获当一个XLS文件被复制到一个目录或在一个目录中创建。
- Filesystemwatcher 't trigger event
- FileSystemWatcher -事件没有第二次触发
- FileSystemWatcher Changed event does 't fire
- FileSystemWatcher -只有更改事件一次触发一次?
监控类:
public class Monitor
{
FileSystemWatcher watcher = new FileSystemWatcher();
readonly string bookedPath = @"''SomeServer'SomeFolder'";
public delegate void FileDroppedEvent(string FullPath);
public event FileDroppedEvent FileDropped;
public delegate void ErrorEvent(Exception ex);
public event ErrorEvent Error;
public Monitor()
{
watcher.Path = bookedPath;
watcher.Filter = "*.xls";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Error += new ErrorEventHandler(watcher_Error);
}
void watcher_Error(object sender, ErrorEventArgs e)
{
Error(e.GetException());
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Created) return;
FileDropped(e.FullPath);
}
public void Start()
{
watcher.EnableRaisingEvents = true;
}
public void Stop()
{
watcher.EnableRaisingEvents = false;
}
}
简单的表单与列表框:
public partial class Form1 : Form
{
Monitor monitor = new Monitor();
public Form1()
{
InitializeComponent();
FormClosing += new FormClosingEventHandler(Form1_FormClosing);
Load += new EventHandler(Form1_Load);
monitor.FileDropped += new Monitor.FileDroppedEvent(monitor_FileDropped);
monitor.Error += new Monitor.ErrorEvent(monitor_Error);
}
void Form1_Load(object sender, EventArgs e)
{
monitor.Start();
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
monitor.Stop();
}
void monitor_Error(Exception ex)
{
listBox1.Items.Add(ex.Message);
}
void monitor_FileDropped(string FullPath)
{
listBox1.Items.Add(FullPath);
}
}
我做错了什么?
试试这个。对于一个非常相似的任务,
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(handler);
watcher.Renamed += new RenamedEventHandler(handler);
这可能是因为文件元数据尚未更新。
您试过以下方法吗:
watcher.Path = directory name;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.xls";
watcher.Changed += OnDirectoryChange;
watcher.Error += OnError;
watcher.EnableRaisingEvents = true;
// Watch only files not subdirectories.
watcher.IncludeSubdirectories = false;
我认为你的问题在于过滤器和事件。NotifyFilters.LastAccess
仅在打开文件时触发。尝试使用:
NotifyFilters.LastWrite | NotifyFilters.CreationTime
这将监视写入/创建的文件。接下来,连接到Created
委托来处理新创建的文件:
watcher.Created += YourDelegateToHandleCreatedFiles
FileSystemWatcher
的工作方式是首先使用NotifyFilters
来限制事件触发器。然后,使用实际事件来完成工作。通过钩接Created
事件,您将只在创建文件时工作。