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

本文关键字:检测 语法 错误 文件 app config | 更新日期: 2023-09-27 18:23:54

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

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

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

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(
    "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
    public static Settings Default { get { return defaultInstance; } }
    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("17")]
    public int SecondSetting
    {
        get { return ((int)(this["SecondSetting"])); }
        set { this["SecondSetting"] = value; }
    }
}

我的C#测试应用程序:

static void Main (string[] args)
{
    try
    {
        Console.WriteLine(AppConfigTests.Properties.Settings.Default.SecondSetting);
    }
    catch (Exception x)
    {
        Console.WriteLine(x.ToString());
    }
}

我的App.config文件的相关部分(请注意,该值不是有效的整数):

<userSettings>
    <AppConfigTests.Properties.Settings>
        <setting name="SecondSetting" serializeAs="String">
            <value>1foo7</value>
        </setting>
    </AppConfigTests.Properties.Settings>
</userSettings>

System.Number.StringToNumber正在抛出System.Format异常,但有东西正在捕获它并将其丢弃,我的catch块从未被输入。在Visual Studio调试器输出中,我发现"mscorlib.dll中首次出现类型为System.FormatException的异常",但这对我没有帮助,只能进一步确认引发了异常。

我试着在Settings.Designer.cs中向我的设置属性添加一个IntegerCs,但没有帮助(我确保.cs不会重新生成)。

我试着在main()方法的顶部添加以下代码,但也无济于事:

foreach (SettingsProperty sp in AppConfigTests.Properties.Settings.Default.Properties)
    sp.ThrowOnErrorDeserializing = true;

我曾想过实现我自己的ConfigurationSection,但我希望有一个更简单的解决方案。

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

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

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

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

  foreach (SettingsPropertyValue propertyValue in AppConfigTests.Properties.Settings.Default.PropertyValues) {
    if (propertyValue.UsingDefaultValue) {
      throw new Exception(propertyValue.Name + " is not deserialized properly.");
    }
  }

如果您正在编写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 {
}

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