在C#中,你可以使用异常处理来处理Watcher可能遇到的异常情况。以下是一个基本的示例,展示了如何在Watcher中处理异常:
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WatcherExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnStartWatcher_Click(object sender, EventArgs e)
{
btnStartWatcher.Enabled = false;
btnStopWatcher.Enabled = true;
Task.Run(() => StartWatcher());
}
private void btnStopWatcher_Click(object sender, EventArgs e)
{
btnStartWatcher.Enabled = true;
btnStopWatcher.Enabled = false;
}
private void StartWatcher()
{
try
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\example_folder";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Watcher started.");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// Handle the change event here.
Console.WriteLine($"File '{e.FullPath}' has been changed.");
}
private void OnRenamed(object source, RenamedEventArgs e)
{
// Handle the rename event here.
Console.WriteLine($"File '{e.OldFullPath}' has been renamed to '{e.FullPath}'.");
}
}
}
在这个示例中,我们创建了一个简单的WinForms应用程序,其中包含一个开始Watcher按钮和一个停止Watcher按钮。当点击开始按钮时,会启动一个新的Watcher任务,该任务将监视指定的文件夹。如果在启动Watcher时发生任何异常,程序将弹出一个包含异常消息的对话框。