尝试实现FileSystemWatcher
但保存文件时会调用OnChanged
函数两次。基于其他一些帖子,我怀疑LastWrite
过滤器有多个事件?我认为NotifyFilters
会将它限制为仅在写入文件时触发,但是其他东西导致函数运行两次。 e.ChangeType
只告诉我文件已更改,但不确切如何更改。有没有办法将此限制为仅运行一次?
public MainWindow()
{
InitializeComponent();
FileSystemWatcher fsw = new FileSystemWatcher(path);
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.EnableRaisingEvents = true;
fsw.Changed += new FileSystemEventHandler(OnChanged);
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
if (newString == null)
{
using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
lastString = sr.ReadToEnd();
}
difference = lastString;
} else {
using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
newString = sr.ReadToEnd();
}
int newCount = newString.Count();
int count = lastString.Count();
// MessageBox.Show("last:" + lastString.Count().ToString(), "next: " + newString.Count());
difference = newString.Remove(0,5);
lastString = newString;
}
Application.Current.Dispatcher.Invoke(new Action(() => { tb_content.Text = difference; }));
MessageBox.Show(e.ChangeType.ToString(), "");
}
}
答案 0 :(得分:2)
您可以自行过滤,因为我已发布here。
答案 1 :(得分:1)
Frederik答案的另一种选择:
我想到的一个小解决方法是阻止OnChanged方法在执行时执行。
例如:
private bool IsExecuting { get; set; }
private void OnChanged(object sender, FileSystemEventArgs e)
{
if (!IsExecuting)
{
IsExecuting = true;
// rest of your code
IsExecuting = false;
}
}