Systemfilewatcher未正确触发已删除事件
本文关键字:删除 事件 Systemfilewatcher | 更新日期: 2023-09-27 18:26:13
我有一个文件查看器:
private void initFileWatcherActive()
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Global.Directory + Global.Machine + "''" + Machines.Directories.Aktiv;
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite;
watcher.IncludeSubdirectories = false;
watcher.Filter = "*.*";
watcher.InternalBufferSize = 24000;
watcher.Created -= new FileSystemEventHandler(OnChangedActive);
watcher.Deleted -= new FileSystemEventHandler(OnChangedActive);
watcher.Created += new FileSystemEventHandler(OnChangedActive);
watcher.Deleted += new FileSystemEventHandler(OnChangedActive);
watcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
setStatus("Filewatcher konnte nicht initialisiert werden: " + ex.Message, Level.ERROR);
}
}
通过此呼叫:
private void OnChangedActive(object source, FileSystemEventArgs e)
{
try
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Created: break;
case WatcherChangeTypes.Deleted:
break;
default:
break;
}
}
catch (Exception ex)
{
this.Dispatcher.BeginInvoke(new Action(() => setStatus(ex.Message, Level.ERROR)));
}
}
如果我在windows资源管理器中添加或删除文件,一切都很好。但在我的场景中,另一个.net程序添加了带有以下代码的文件:
public static void add(String path, MachineOrder machineOrder, String fileExtention)
{
String filePath = path;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Auftragsnummer;" + machineOrder.Ordernumber);
stringBuilder.AppendLine("Positionsnummer;" + machineOrder.Positionnumber);
stringBuilder.AppendLine("Aenderungsdatum;" + machineOrder.Editdate.ToString("yyyy-MM-dd hh:mm:ss"));
stringBuilder.AppendLine("Menge;" + machineOrder.Amount.ToString());
stringBuilder.AppendLine("Menge fertig;" + machineOrder.AmountReady.ToString());
stringBuilder.AppendLine("Termin;" + machineOrder.Deliverydate.ToString("yyyy-MM-dd"));
stringBuilder.AppendLine("Kundennummer;" + machineOrder.Customernumber);
stringBuilder.AppendLine("Kundenname;" + machineOrder.Customername);
stringBuilder.AppendLine("Kdauf.-nummer;" + machineOrder.CustomerOrdernumber);
stringBuilder.AppendLine("Kdauf.-positionsnummer;" + machineOrder.CustomerOrdernumber);
stringBuilder.AppendLine("Modell;" + machineOrder.Modell);
foreach (KeyValuePair<String, string> characteristic in machineOrder.Charakteristics)
{
stringBuilder.AppendLine(characteristic.Key + ";" + characteristic.Value);
}
String filename = FilenameBuilder.buildFilename(machineOrder, fileExtention);
filePath = filePath + "''" + filename;
System.IO.File.WriteAllText(filePath, stringBuilder.ToString());
}
现在文件观察者跳转到创建、删除、创建、删除等等。我不知道为什么
有什么想法吗?
看起来您正在实例化多个FileSystemWatcher
实例,可能是无意的。
initFileWatcherActive
创建一个新实例,删除事件处理程序,并添加新的处理程序。您正试图从一个全新的实例中删除处理程序,这一事实让我认为您多次调用此函数,可能是想从现有实例中移除处理程序。这将导致多个观察者观看同一目录,并使事件看起来发生不止一次。
您可能应该在更高的范围内声明一个观察程序,并且只实例化一次。