简体   繁体   中英

Catching exceptions thrown by the FileSystemWatcher listener thread

I am trying to figure out a way to catch exceptions thrown by FileSystemWatcher these seem to happen randomly as I have noticed from the crash reports logs for my software. The crash is not frequent as it only happened twice last month but its annoying and I would love to fix it. The exception in question seems to be related to files having invalid characters in their paths. I am not sure if that is the case or if the event raised is malformed. So far all I know is the stack trace of the exception:

Top-level Exception
Type:        System.ArgumentException
Message:     Illegal characters in path.
Source:      mscorlib

    Stack Trace: 
    at System.IO.Path.GetFileName(String path)

    at System.IO.FileSystemWatcher.MatchPattern(String relativePath)

    at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)

    at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes,   NativeOverlapped* overlappedPointer)

    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

From the stack trace it is clear that the exception is raised within the execution context of the listener before raising the callback events to my application. I was wondering if there is anyway to catch such an exception and continue execution, ignoring the event.

I tried encapsulating my watcher callbacks' body with try/catch blocks but it seems that the execution never reaches the callbacks and its really frustrating as I am now starting to think that it is a bug in the .Net framework

Have you tried registering the OnError event?

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.onerror%28v=vs.110%29.aspx

EDIT:

The only thing left is ThreadException and UnhandledException:

    // Add handler to handle the exception raised by main threads
    Application.ThreadException += 
    new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

    // Add handler to handle the exception raised by additional threads
    AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM