0

我正在尝试在 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;
    }
4

1 回答 1

1

FileSystemWatcher从新线程调用事件,如果要更新任何控件,则必须返回InvokeUI 线程

 private void writeTb(object source, FileSystemEventArgs e)
 {
    base.Invoke((Action)delegate
    {
       textBox1.Text += e.ChangeType + ": " + e.FullPath;
    });
 }
于 2013-03-19T00:20:15.133 回答