Search code examples
c#visual-studio-2010filesystemwatcher

FileSystemWatcher preventing debugger from capturing exception


I've been driving myself nuts trying to figure this one out today. I've been using FileSystemWatcher for a while now to capture file changes. one of my projects that was originally on framework 3.5 was moved to 4.0 to take advantage of some EF stuff and it seems to have affected how visual studio allows me to debug code that takes advantage of FileSystemWatcher. Here's a small example of the problem i'm having (see watcher_Changed):

class Program
{
    static void Main(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(@"C:\inputFolder\");

        watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        watcher.NotifyFilter = NotifyFilters.LastAccess
            | NotifyFilters.LastWrite
            | NotifyFilters.FileName
            | NotifyFilters.DirectoryName;

        Console.WriteLine("Ready");

        watcher.EnableRaisingEvents = true;
        Thread.Sleep(System.Threading.Timeout.Infinite);
    }

    static void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        //This exception here (just an example), does not get sent to the debugger, rather it goes to the
        //console and then the application exits
        throw new ArgumentException();
    }
}

The code will always close for me after tossing the ArgumentException to the console. This is causing some major debugging issues for me in more complex scenarios.

Any Ideas?


Solution

  • I think this is because Visual Studio is not configured to break when System.ArgumentException is thrown, but when it is user-handled. As the exception is occuring in a thread created by the FileSystemWatcher it probably doesn't have any kind of top level exception handler.

    To change the debugging settings go to Debug\Exceptions and then expand Common Language Runtime Exceptions and search for the exception. Alternatively use the Find... button. Then make sure the "Thrown" checkbox is ticked. Be warned that you probably don't want this option normally as many applications will probably handle the exception normally.