如何加载.NET应用程序的WinForm user.config文件时,赶上异常?应用程序、加载、异常、文件

2023-09-03 20:54:58 作者:孤独换杯酒

有时候,在使用默认配置系统。NET(2.0)WinForm的桌面应用程序,该 user.config 文件将被破坏,不能再加载(当配置系统试图加载它,它会抛出一个 System.Xml.XmlException )。

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).

撇开为什么该文件得到摆在首位损坏的问题(也许是宇宙射线,或HDD的问题,还是其他什么东西你无法控制),问题就变成了怎么能一个陷阱这个异常并做一些有意义的事情呢?

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?

微软的Connect网站对这类问题的报告。不幸的是,他们的报告是不是非常有帮助。

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# - 用户设置打破

在我的情况下,(WinForms应用程序),异常处理程序我有我的父母(启动)的形式捕获该异常。但是,我想你可以使用 MyApplication_UnhandledException 处理程序 ApplicationEvents 为好。底线是,你需要一些高层次的未处理的异常处理程序来捕获这一点。

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_UnhandledException handler in ApplicationEvents as well. Bottom line is, you need some sort of high-level "unhandled exception" handler to catch this.

此外,你可以看看异常的的InnerException,看看它是否是类型 System.Configuration.ConfigurationErrorsException 。如果是,那么你可以看看这个的InnerException的 .FileName 属性来获取user.config文件的完整文件名。

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 .FileName property 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.