C# 如何在app.config文件中检测值语法错误?

C# 如何在app.config文件中检测值语法错误?,c#,.net,settings,app-config,system.configuration,C#,.net,Settings,App Config,System.configuration,我需要改进app.config文件中的错误报告 我有一个小小的测试应用程序,其中包含一个“int”类型的设置。如果我在app.config中将其值更改为无效的整数,我希望引发一个异常,我可以捕获并报告该异常。不幸的是,有些东西正在吞噬这个例外。有没有一种简单的方法来防止这种行为并让异常传播出去 My Settings.Designer.cs文件(由Visual Studio生成): 我的C#测试应用程序: static void Main (string[] args) { try

我需要改进app.config文件中的错误报告

我有一个小小的测试应用程序,其中包含一个“int”类型的设置。如果我在app.config中将其值更改为无效的整数,我希望引发一个异常,我可以捕获并报告该异常。不幸的是,有些东西正在吞噬这个例外。有没有一种简单的方法来防止这种行为并让异常传播出去

My Settings.Designer.cs文件(由Visual Studio生成):

我的C#测试应用程序:

static void Main (string[] args)
{
    try
    {
        Console.WriteLine(AppConfigTests.Properties.Settings.Default.SecondSetting);
    }
    catch (Exception x)
    {
        Console.WriteLine(x.ToString());
    }
}
my App.config文件的相关部分(请注意,该值不是有效的整数):

我曾想过实现我自己的配置部分,但我希望有一个更简单的解决方案

重申一下:我需要一种方法来报告app.config文件中设置值的错误

(如果我在App.config中破坏了XML语法(例如,通过删除一个尖括号),我的catch块会得到一个很好的异常,包含我可以要求的所有细节。)

您可以这样做(假设您在App.config中覆盖了所有设置值):

如果您正在编写web应用程序,当反序列化失败时,它将触发此事件:

try {
  if (this.IsHostedInAspnet()) {
    object[] args = new object[] { this.Property, this, ex };
    Type type = Type.GetType("System.Web.Management.WebBaseEvent, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
    type.InvokeMember("RaisePropertyDeserializationWebErrorEvent", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, args, CultureInfo.InvariantCulture);
  }
}
catch {
}

否则,它将返回默认值,所以您唯一能做的就是遍历所有值并检查它们是否为默认值。

我很好奇您为此做了什么,因为我遇到了类似的问题。。。
<userSettings>
    <AppConfigTests.Properties.Settings>
        <setting name="SecondSetting" serializeAs="String">
            <value>1foo7</value>
        </setting>
    </AppConfigTests.Properties.Settings>
</userSettings>
foreach (SettingsProperty sp in AppConfigTests.Properties.Settings.Default.Properties)
    sp.ThrowOnErrorDeserializing = true;
  foreach (SettingsPropertyValue propertyValue in AppConfigTests.Properties.Settings.Default.PropertyValues) {
    if (propertyValue.UsingDefaultValue) {
      throw new Exception(propertyValue.Name + " is not deserialized properly.");
    }
  }
try {
  if (this.IsHostedInAspnet()) {
    object[] args = new object[] { this.Property, this, ex };
    Type type = Type.GetType("System.Web.Management.WebBaseEvent, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
    type.InvokeMember("RaisePropertyDeserializationWebErrorEvent", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, args, CultureInfo.InvariantCulture);
  }
}
catch {
}