-1

I am trying to write a simple application that lists changes to a directory. I used the microsoft documentation as a starting point and I am scratching my head as to why the code will not work in my WPF application, it works fine as a console application.

Currently, this is what I have in MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Syncio
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            using var watcher = new FileSystemWatcher(@"C:\Users\Connor\Desktop\Test");

            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;

            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;
            watcher.Error += OnError;

            watcher.Filter = "*.txt";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;


        }

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            MessageBox.Show($"Changed: {e.FullPath}");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            string value = $"Created: {e.FullPath}";
            MessageBox.Show(value);
        }

        private void OnDeleted(object sender, FileSystemEventArgs e) =>
            Debug.WriteLine($"Deleted: {e.FullPath}");

        private void OnRenamed(object sender, RenamedEventArgs e)
        {
            MessageBox.Show($"Renamed:");
            MessageBox.Show($"    Old: {e.OldFullPath}");
            MessageBox.Show($"    New: {e.FullPath}");
        }

        private void OnError(object sender, ErrorEventArgs e) =>
            PrintException(e.GetException());

        private void PrintException(Exception? ex)
        {
            if (ex != null)
            {
                MessageBox.Show($"Message: {ex.Message}");
                MessageBox.Show("Stacktrace:");
                MessageBox.Show(ex.StackTrace);
                PrintException(ex.InnerException);
            }
        }
    }
}

The reason I have it displaying the events as a message box is because debug statements weren't working. As I said above, I can get this to work fine in a console application per this tutorial for microsoft: https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-6.0

Yet it will not work in WPF, what am I missing here? None of the events are firing. I am starting off easily, so I am just filtering by text files.

Connor
  • 113
  • 8
  • Related: [FileSystemWatcher not firing events](https://stackoverflow.com/questions/16278783/filesystemwatcher-not-firing-events) – Theodor Zoulias Dec 13 '21 at 22:22

2 Answers2

0

Declaring 'watcher' as a global variable works for me.

 private FileSystemWatcher watcher = new FileSystemWatcher();
 public MainWindow()
            {
                InitializeComponent();       
                watcher.Path = @"C:\Users\Connor\Desktop\Test";
PrimoPyo
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 26 '22 at 19:36
-1

I've figured it out, for any future reader change:

using var watcher = new FileSystemWatcher(@"path/to/file"); 

to

FileSystemWatcher watcher = new FileSystemWatcher(@"path/to/file")

Odd, but now it works.

Connor
  • 113
  • 8
  • 2
    The `using` statement means that it goes out of scope when the method is done executing and it gets disposed. Even without the `using` I still wouldn't trust it not to get disposed at some point. If you assign it to a field within the class then it won't go out of scope before the class that contains it does. – Scott Hannen Dec 13 '21 at 22:19
  • Thank you for the tip/info Scott, I will make that correction! – Connor Dec 13 '21 at 22:49