Sugitime
Sugitime

Reputation: 1888

Windows form crashing when file monitor events are triggered

I am trying to implement file monitoring into a windows form app, and I am running into an issue. My form keeps crashing when ever the events are triggered.

    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;
    }

Upvotes: 0

Views: 131

Answers (1)

sa_ddam213
sa_ddam213

Reputation: 43636

The FileSystemWatcher events are called from a new thread, you will have to Invoke back to the UI thread if you want to update any controls

 private void writeTb(object source, FileSystemEventArgs e)
 {
    base.Invoke((Action)delegate
    {
       textBox1.Text += e.ChangeType + ": " + e.FullPath;
    });
 }

Upvotes: 1

Related Questions