使用FileSystemWatcher监视何时在同一实例上加载两个文件

时间:2019-02-21 12:40:58

标签: filesystemwatcher

打开文件时将调用以下方法:

     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();
    }

1。我很失望,仅当保存一个实例中的文件时才得到MessageBox,但我想在第二个实例上加载文件时收到消息。主要问题是用户两次打开了应用程序,现在可以在两种情况下进行修改。为了节省,我使用这种方法:

公共重写void WriteStartObject(XmlDictionaryWriter writer,对象图);

此NotifyFilters.LastAccess是否有效?对我来说,NotifyFilters.LastWrite似乎可以工作...

  1. 另一个小问题是,在一个实例上保存对文件的更改后,messageBox出现了两次(好像我没有足够的问题)。

0 个答案:

没有答案