//声明传递FileSystemEventArgs对象的委托
private delegate void setLogTextDelegate(FileSystemEventArgs e);
//创建监听
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "正在监听中……";
FileSystemWatcher watch = new FileSystemWatcher();
watch.Path = @"f:\";
watch.Filter = "a.css";
watch.NotifyFilter = NotifyFilters.LastWrite;
watch.Changed+=new FileSystemEventHandler(watch_Changed);
watch.EnableRaisingEvents = true;
}
//监听到变化后的事件,跨线程
private void watch_Changed(object source, FileSystemEventArgs e)
{
//判断是否跨线程
if (this.InvokeRequired)
{
//使用委托将方法封送到UI主线程处理
this.Invoke(new setLogTextDelegate(showMain), new object[] { e });
}
}
//主线程UI
private void showMain(FileSystemEventArgs e)
{
this.label1.Text = e.FullPath;
}
注意:文件更新后watch_Changed事件会被触发两次。最简单的解决方法就是接受到事件后,立刻关闭监听。处理结束后,重新启动监听。