【发布时间】:2022-01-17 06:56:35
【问题描述】:
我正在尝试编写一个简单的应用程序来列出对目录的更改。我使用 microsoft 文档作为起点,我正在摸索为什么代码在我的 WPF 应用程序中无法运行,它作为控制台应用程序运行良好。
目前,这是我在 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);
}
}
}
}
我将事件显示为消息框的原因是调试语句不起作用。正如我上面所说,我可以按照本教程为微软在控制台应用程序中正常工作: https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-6.0
但它在 WPF 中不起作用,我在这里缺少什么?没有任何事件正在触发。我开始很容易,所以我只是按文本文件过滤。
【问题讨论】:
标签: c# wpf visual-studio .net-core filesystemwatcher