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.