Search code examples
c#visual-studio-2010filesystemwatcher

Why is FileSystemWatcher closing the program?


I have:

using System.IO;
using System.Windows.Forms;

namespace myNamespace1
{
    public partial class Form1 : Form
    {
        FileSystemWatcher watcher = new FileSystemWatcher();

        public Form1()
        {
            InitializeComponent();

            watcher.Path = @"c:\users\Me\desktop\z";
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.EnableRaisingEvents = true;
        }

        void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Text = e.Name + " " + e.ChangeType.ToString();
        }

    }
}

When I add a folder or file to the folder (-z) – the program closes. Why?

I'm running in Debug mode. And I don't get any exception from VS.

EDIT:

The answer:

jon-skeet's answer

+(in a comment)

In Visual Studio, can you go to the Debug Menu -> Exceptions. On this dialog, make sure that next to Common Language Runtime Exceptions, make sure both 'Thrown' and 'User Unhandled' are ticked, click OK and try debugging again. – dash


Solution

  • Assuming Text is trying to change a UI property, you're changing the UI from the wrong thread. FileSystemWatcher raises events on thread-pool threads, but you're only meant to access the UI from the UI thread. That's probably throwing an exception in the thread-pool thread, which is bringing down the process.

    Try this instead:

    void watcher_Created(object sender, FileSystemEventArgs e)
    {
        Action action = () => Text = e.Name + " " + e.ChangeType;
        // Or Dispatcher.Invoke - it depends on your application type
        Invoke(action);
    }