Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Config File: How to check if ConfigSection is present

Tags:

c#

.net

Consider:

The line:

<section name="unity" />

The block:

<unity>
    <typeAliases />
    <containers />
</unity>

Say the line is available in the .config file while the block is missing.

How to programmatically check if the block exists or not?

[EDIT]

For those who geniuses, who were quick to mark the question negative:

I have already tried ConfigurationManager.GetSection()

and

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

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

var sInfo = section.SectionInformation;

var isDeclared = sInfo.IsDeclared;

Correct me if I'm mistaken, above does not return a null if the <configSections> is defined (even though the actual unity block is missing).

like image 435
dan Avatar asked May 02 '14 14:05

dan


3 Answers

Since ConfigurationSection inherits from ConfigurationElement you can use the ElementInformation property to tell if the actual element was found after deserialization.

Use this method to detect whether the ConfigurationSection element is missing in the config file:

//After Deserialization
if(customSection.ElementInformation.IsPresent == false)
    Console.WriteLine("Section Missing");

To determine if a certain element was missing, you can use the property within the section (lets pretend it's called 'propName'), get propName's ElementInformation property and check the IsPresent flag:

if(customSection.propName.ElementInformation.IsPresent == false)
    Console.WriteLine("Configuration Element was not found.");

   

Of course if you want to check if the <configSections> definition is missing, use the following method:

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

if(mySection is null)
    Console.WriteLine("ConfigSection 'MySection' was not defined.");

-Hope this helps

like image 117
Kyle B Avatar answered Oct 23 '22 21:10

Kyle B


Use ConfigurationManager.GetSection. This will return null if the section does not exist.

Return Value

Type: System.Object

The specified ConfigurationSection object, or null if the section does not exist.

if (ConfigurationManager.GetSection("unity") == null)
{
    Console.WriteLine("Section does not exist");
}
like image 36
RB. Avatar answered Oct 23 '22 21:10

RB.


Here is how I solved this problem.

var unitySection = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
if (unitySection != null && unitySection.Containers.Count != 0)
    container.LoadConfiguration();

The first check is for the definition, the second for the block

like image 2
Craig Avatar answered Oct 23 '22 23:10

Craig