我正在尝试在 Windows 窗体应用程序中实现文件监控,但遇到了问题。每当触发事件时,我的表单就会不断崩溃。
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "";
FileSystemWatcher watch = new FileSystemWatcher();
watch.Path = @"C:\files\";
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watch.Filter = "*.txt";
watch.Changed += new FileSystemEventHandler(writeTb);
watch.Created += new FileSystemEventHandler(writeTb);
watch.Deleted += new FileSystemEventHandler(writeTb);
watch.Renamed += new RenamedEventHandler(writeTb);
watch.EnableRaisingEvents = true;
}
private void writeTb(object source, FileSystemEventArgs e)
{
textBox1.Text += e.ChangeType + ": " + e.FullPath;
}