Monitor when two files are loaded on the same instance using FileSystemWatcher

  • Thread starter Thread starter Quitty15
  • Start date Start date
Q

Quitty15

Guest

The following method is called when a file is open:

private void Load(string fileName)
{
// Only watch seq files.
this.watcher.Path = Path.GetDirectoryName(fileName);

// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
this.watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
this.watcher.Filter = Path.GetFileName(fileName);

// Begin watching.
this.watcher.EnableRaisingEvents = true;

// Add event handlers.
this.watcher.Changed += this.OnChanged;

// code for opening file asynchronously
}

private void OnChanged(object source, FileSystemEventArgs e)
{
App.Current.Dispatcher.Invoke(() =>
{
MessageBoxResult result = CustomMessageBox.ShowYesNoCancel(
"The file has been modified by another instance.",
"More instances are opened!",
"Overwrite",
"Reload",
"Save as",
MessageBoxImage.Exclamation);

if (result == MessageBoxResult.Yes)
{
// Overwrite
}

if (result == MessageBoxResult.Cancel)
{
// Save as;
}


if (result == MessageBoxResult.No)
{
// reload file and lose changes

}
});
var t = new System.Timers.Timer();
((FileSystemWatcher)source).Changed -= new FileSystemEventHandler(this.OnChanged);
t.Interval = 1000;
t.Elapsed += new ElapsedEventHandler(Elapsed);
t.Start();
}

private static void Elapsed(object sender, ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
}


private static void Elapsed(object sender, ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
}


1.I'm very disappointed that I get my MessageBox only when the file from one instances is saved but I like to have my message when I load the file on the second instance. Main problem is that the user opened the application twice and now is possible to modified in both instances. For saving I'm using this method:

public override void WriteStartObject(XmlDictionaryWriter writer, object graph);

Is this NotifyFilters.LastAccess working? For me just NotifyFilters.LastWrite seems to work...

  1. The other small problem is that after I save the changes to my file on one instances the messageBox appear twice(as if I do not have enough problems).




Continue reading...
 
Back
Top