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