我想使用FSW监视文件何时由我的应用程序的同一实例打开和修改。我希望仅当我保存在同一应用程序(我们的应用程序)中两次打开过的文件时,才触发监视程序。我的问题是,即使我只打开了一个应用程序实例,也会触发该监视程序。在另一个应用程序实例中保存(修改)一个文件或从当前应用程序实例中保存相同的文件,我该如何区分?
我尝试使用集合,尝试在程序的不同部分制作this.watcher.EnableRaisingEvents = true
或this.watcher.EnableRaisingEvents = false
,但似乎没有什么能解决我的问题。
这是我的代码段:
private void Load(string fileName)
{
// Only watch seq files.
this.watcher.Path = Path.GetDirectoryName(fileName);
// Watch for changes in LastWrite times.
this.watcher.NotifyFilter = NotifyFilters.LastWrite;
this.watcher.Filter = "*.zzz";
// Add event handlers.
this.watcher.Changed += this.OnChanged;
// Begin watching.
this.watcher.EnableRaisingEvents = true;
// opened file
}
// Define the event handlers.
private void OnChanged(object source, FileSystemEventArgs e)
{
App.Current.Dispatcher.Invoke(() =>
{
MessageBoxResult result = CustomMessageBox.ShowYesNoCancel(
"The file has been modified by another instance.",
"More app instances are opened!",
"Overwrite",
"Reload",
"Save as",
MessageBoxImage.Exclamation);
if (result == MessageBoxResult.Yes)
{
// Overwrite
this.SaveSequence();
}
if (result == MessageBoxResult.Cancel)
{
// Save as
}
if (result == MessageBoxResult.No)
{
// Reload file and lose changes
}
});
// End watching.
this.watcher.EnableRaisingEvents = false;
}
internal bool Save()
{
/// some code
this.File.Write(this.FilePath); //here is the moment when my watcher is triggered
/// rest of the code
}