我的FileSystemWatcher没有抛出任何事件。我看过这些类似的问题,似乎都没有解决我的问题:
*编辑:我的目标是捕获何时将XLS文件复制到目录中或在目录中创建。
监控类:
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;
}
}
使用Listbox的简单表单:
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);
}
}
我做错了什么?
答案 0 :(得分:2)
试一试。对我来说非常类似的任务。
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(handler);
watcher.Renamed += new RenamedEventHandler(handler);
答案 1 :(得分:0)
这可能是因为文件元数据尚未更新。如果您不断写入文件,可能会发生这种情况。
答案 2 :(得分:0)
您是否尝试过以下操作:
{{1}}
答案 3 :(得分:-1)
您的问题与过滤器以及我认为的事件有关。 NotifyFilters.LastAccess
仅在文件打开时触发。尝试使用:
NotifyFilters.LastWrite | NotifyFilters.CreationTime
这将监视已写入/创建的文件。接下来,连接到Created
委托以处理新创建的文件:
watcher.Created += YourDelegateToHandleCreatedFiles
FileSystemWatcher
的工作方式是首先使用NotifyFilters
来限制事件触发器。然后,您使用实际事件来完成工作。通过挂钩Created
事件,您只能在创建文件时才能工作。