Как определить отсутствующий элемент конфигурации?

1

Используя 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:

Проблема

Я не могу найти способ различать пустой, но существующий элемент конфигурации и случай, когда весь элемент конфигурации оставлен без внимания.

Я хочу иметь это, потому что, если присутствует элемент, я хочу убедиться, что он проходит определенную логику проверки, но также прекрасно оставить элемент полностью.

Теги:
configuration
configurationmanager

2 ответа

1
Лучший ответ

Вы можете найти раздел:

var sections = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections;
var exists = sections.Cast<ConfigurationSection>()
                .Any(x => x.SectionInformation.Type.StartsWith("MissingConfigElementTest.MyConfigurationSection"));
  • 0
    Благодарю. Это похоже на решение (хотя оно требует некоторых настроек для работы в веб-контексте, которым является мое настоящее приложение). Однако это пахнет как хак, я надеялся, что что-то будет, когда конфиг загружен через ConfigurationManager .
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>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню