Reputation: 69260
Using System.Configuration
, how can I identify if a child configuration element is completely missing, or merely empty?
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>
The output is
Empty.Name:
Missing.Name:
I can't find a way to differentiate between the empty, but present configuration element and the case where the entire configuration element has been left out.
I want to have this because if an element is present, I want to make sure that it passes certain validation logic, but it is also fine to just leave the element out entirely.
Upvotes: 2
Views: 1061
Reputation: 176
To add to this, the ElementInformation.IsPresent property can be used to determine whether the element exists within the original configuration.
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( );
This will output
Empty.Name:
Missing.Name: <NULL>
Upvotes: 5
Reputation: 101150
You can search for the section:
var sections = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections;
var exists = sections.Cast<ConfigurationSection>()
.Any(x => x.SectionInformation.Type.StartsWith("MissingConfigElementTest.MyConfigurationSection"));
Upvotes: 2