我有一个应用程序,我正在寻找一个文本文件,如果对文件做了任何更改,我使用OnChanged事件处理程序来处理事件。我正在使用NotifyFilters。LastWriteTime,但是事件仍然被触发两次。这是代码。
public void Initialize()
{
FileSystemWatcher _fileWatcher = new FileSystemWatcher();
_fileWatcher.Path = "C:\\Folder";
_fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
_fileWatcher.Filter = "Version.txt";
_fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
_fileWatcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
.......
}
在我的情况下,OnChanged被调用两次,当我改变文本文件version.txt并保存它。
代码可自定义禁用阻止第二个观察者升起的时间间隔,如果他们存在,则不阻止观察者:
namespace Watcher
{
class Static
{
public static DateTime lastDomain { get; set; }
public static string lastDomainStr { get; set; }
}
public partial class Form1 : Form
{
int minMs = 20;//time for blocking in ms
public Form1()
{
InitializeComponent();
Static.lastDomain = new DateTime(1970, 1, 1, 0, 0, 0);
Static.lastDomainStr = "";
Start();
}
private void Start()//Start watcher
{
//...
domain.Changed += new FileSystemEventHandler(Domain);
domain.EnableRaisingEvents = true;
//...you second unblocked watchers
second.Changed += new FileSystemEventHandler(Second);
second.EnableRaisingEvents = true;
}
private void Domain(object source, FileSystemEventArgs e)
{
if (now.Subtract(Static.lastDomain).TotalMilliseconds < minMs && Static.lastDomainStr == e.FullPath)return;
//...you code here
/* if you need form access
this.Invoke(new MethodInvoker(() =>{ textBox1.Text = "...";}));
*/
Static.lastDomain = DateTime.Now;
Static.lastDomainStr = e.FullPath;
}
private void Second(object source, FileSystemEventArgs e)
{
//...Second rised
}
}
}