如何识别丢失的ConfigurationElement?

时间:2014-08-22 11:51:53

标签: c# .net configuration configurationmanager

使用System.Configuration,如何确定子配置元素是完全缺失还是仅为空?

测试程序

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MissingConfigElementTest
{
    class MyConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)base["name"]; }
        }
    }

    class MyConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("empty", DefaultValue = null)]
        public MyConfigurationElement Empty
        {
            get { return (MyConfigurationElement)base["empty"]; }
        }

        [ConfigurationProperty("missing", DefaultValue = null)]
        public MyConfigurationElement Missing
        {
            get { return (MyConfigurationElement)base["missing"]; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var configSection = (MyConfigurationSection)ConfigurationManager.GetSection("mySection");

            Console.WriteLine("Empty.Name: " + (configSection.Empty.Name ?? "<NULL>"));
            Console.WriteLine("Missing.Name: " + (configSection.Missing.Name ?? "<NULL>"));

            Console.ReadLine();
        }
    }
}

测试配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="mySection" type="MissingConfigElementTest.MyConfigurationSection, MissingConfigElementTest"/>
  </configSections>
  <mySection>
    <empty />
  </mySection>
</configuration>

输出

输出

Empty.Name: 
Missing.Name:

问题

我找不到一种方法来区分空的但是现有的配置元素以及整个配置元素被遗漏的情况。

我想拥有这个,因为如果存在一个元素,我想确保它通过某些验证逻辑,但是将元素完全保留下来也没关系。

2 个答案:

答案 0 :(得分:2)

要添加到此,可以使用ElementInformation.IsPresent属性来确定元素是否存在于原始配置中。

var configSection = ( MyConfigurationSection ) ConfigurationManager.GetSection( "mySection" );

Console.WriteLine( "Empty.Name: " + ( configSection.Empty.ElementInformation.IsPresent ? configSection.Empty.Name : "<NULL>" ) );
Console.WriteLine( "Missing.Name: " + ( configSection.Missing.ElementInformation.IsPresent ? configSection.Missing.Name : "<NULL>" ) );

Console.ReadLine( );

这将输出

Empty.Name:
Missing.Name: <NULL>

答案 1 :(得分:1)

您可以搜索以下部分:

var sections = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections;
var exists = sections.Cast<ConfigurationSection>()
                .Any(x => x.SectionInformation.Type.StartsWith("MissingConfigElementTest.MyConfigurationSection"));