加载.NET WinForm应用程序的user.config文件时如何捕获异常? [英] How to catch exception when loading .NET WinForm app user.config file?

查看:292
本文介绍了加载.NET WinForm应用程序的user.config文件时如何捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时在使用默认配置系统的.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?

,不幸的是他们的报告并不是很有帮助。

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应用程序),我的父(启动)窗体中的异常处理程序捕获此异常。但是我想您可以在 ApplicationEvents 中使用 MyApplication_UnhandledException 处理程序。底线是,你需要一些高级的未处理的异常处理程序来捕获这个。

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.

这篇关于加载.NET WinForm应用程序的user.config文件时如何捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆