我有一个应用程序,我正在寻找一个文本文件,如果对文件做了任何更改,我使用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并保存它。
我知道这是一个老问题,但我遇到了同样的问题,上面的解决方案都没有真正解决我所面临的问题。我已经创建了一个字典,它将文件名与LastWriteTime映射。因此,如果文件不在字典中,将继续执行该进程,否则将检查最后一次修改时间是什么时候,如果与字典中的时间不同,则运行代码。
Dictionary<string, DateTime> dateTimeDictionary = new Dictionary<string, DateTime>();
private void OnChanged(object source, FileSystemEventArgs e)
{
if (!dateTimeDictionary.ContainsKey(e.FullPath) || (dateTimeDictionary.ContainsKey(e.FullPath) && System.IO.File.GetLastWriteTime(e.FullPath) != dateTimeDictionary[e.FullPath]))
{
dateTimeDictionary[e.FullPath] = System.IO.File.GetLastWriteTime(e.FullPath);
//your code here
}
}
我可以通过添加一个函数来检查缓冲区数组中的重复项来做到这一点。
然后使用计时器在数组X时间内未被修改后执行该操作:
-每次有东西写入缓冲区时重置计时器
—对tick执行动作
这还捕获了另一种复制类型。如果修改文件夹内的文件,该文件夹也会引发Change事件。
Function is_duplicate(str1 As String) As Boolean
If lb_actions_list.Items.Count = 0 Then
Return False
Else
Dim compStr As String = lb_actions_list.Items(lb_actions_list.Items.Count - 1).ToString
compStr = compStr.Substring(compStr.IndexOf("-") + 1).Trim
If compStr <> str1 AndAlso compStr.parentDir <> str1 & "\" Then
Return False
Else
Return True
End If
End If
End Function
Public Module extentions
<Extension()>
Public Function parentDir(ByVal aString As String) As String
Return aString.Substring(0, CInt(InStrRev(aString, "\", aString.Length - 1)))
End Function
End Module
我花了大量时间使用FileSystemWatcher,这里的一些方法将不起作用。我真的很喜欢禁用事件的方法,但不幸的是,它不工作,如果有>1文件被丢弃,第二个文件将错过大多数,如果不是所有的时间。
所以我使用以下方法:
private void EventCallback(object sender, FileSystemEventArgs e)
{
var fileName = e.FullPath;
if (!File.Exists(fileName))
{
// We've dealt with the file, this is just supressing further events.
return;
}
// File exists, so move it to a working directory.
File.Move(fileName, [working directory]);
// Kick-off whatever processing is required.
}
代码可自定义禁用阻止第二个观察者升起的时间间隔,如果他们存在,则不阻止观察者:
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
}
}
}