.NET配置文件:如何检查ConfigSection是否存在

dan*_*dan 10 .net c#

考虑:

这条线:

<section name="unity" />

块:

<unity>
    <typeAliases />
    <containers />
</unity>
Run Code Online (Sandbox Code Playgroud)

假设在块丢失时该行在.config文件中可用.

如何以编程方式检查块是否存在?

[编辑]

对于那些天才的人来说,他们很快就将问题标记为否定:

我已经尝试过了 ConfigurationManager.GetSection()

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

var section = config.GetSection("unity");

var sInfo = section.SectionInformation;

var isDeclared = sInfo.IsDeclared;
Run Code Online (Sandbox Code Playgroud)

纠正我,如果我错了,上面并没有返回空值,如果<configSections>被定义(即使实际的统一块丢失).

Kyl*_*e B 15

我在搜索这篇文章的答案时发现了这篇文章.我想我会回来并发布答案,因为我已经解决了它.

由于ConfigurationSection继承自ConfigurationElement,因此您可以使用ElementInformation来判断在反序列化后是否找到了实际元素.

使用此方法检测配置文件中是否缺少ConfigurationSection元素.ConfigurationSection中的以下方法来自它对ConfigurationElement的继承:

//After Deserialization
if(!customSection.ElementInformation.IsPresent)
    Console.WriteLine("Section Missing");
Run Code Online (Sandbox Code Playgroud)

要确定某个元素是否缺失,您可以使用该部分中的属性(让我们假设它称为'PropName'),获取PropName的ElementInformation属性并检查IsPresent标志:

if(!customSection.propName.ElementInformation.IsPresent)
    Console.WriteLine("Configuration Element was not found.");
Run Code Online (Sandbox Code Playgroud)

当然,如果要检查是否缺少<configSections>定义,请使用以下方法:

CustomSection mySection = 
    config.GetSection("MySection") as CustomSection;

if(mySection == null)
    Console.WriteLine("ConfigSection 'MySection' was not defined.");
Run Code Online (Sandbox Code Playgroud)

-希望这可以帮助