Sometimes in .NET (2.0) WinForm desktop apps which use the default configuration system, the user.config file will become corrupted and can’t be loaded anymore (when the configuration system tries to load it, it’ll throw a System.Xml.XmlException).
Putting aside the question of “why did the file get corrupted in the first place” (maybe it was cosmic rays, or HDD problems, or something else you can’t control), the question then becomes “how can one catch this exception and do something meaningful with it?
Microsoft’s Connect site has a report on this sort of problem. Unfortunately, their report isn’t very helpful.
Is it possible to catch exceptions that originate in the default configuration system loader itself? Or would you have to roll your own configuration system to be able to catch this type of exception?
Turns out you can catch this exception. The hint I needed came from this question:
C# – User Settings broken
In my case, (WinForms app), the exception handler I have in my parent (startup) form catches this exception. But I suppose you could use the
MyApplication_UnhandledExceptionhandler inApplicationEventsas well. Bottom line is, you need some sort of high-level “unhandled exception” handler to catch this.Additionally, you can look at the exception’s InnerException and see if it is of type
System.Configuration.ConfigurationErrorsException. If it is, then you can look at the.FileNameproperty of this InnerException to get the full file name of the user.config file.Once you have this, you can do something about it – try to check its contents to see what’s wrong with it, or (worst case) delete it and restart the app so it is re-created with all the default settings.
As I said before, this is a very rare exception, probably caused by sudden system shutdowns or other uncontrollable events (e.g., power outage). Nevertheless, it is nice to finally be able to do something about it.