在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時發生任何異常,程序將彈出一個包含異常消息的對話框。