问题
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
回答1:
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);
来源:https://stackoverflow.com/questions/21450296/catching-exceptions-thrown-by-the-filesystemwatcher-listener-thread