dan
dan

Reputation: 1954

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

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).

Upvotes: 11

Views: 7797

Answers (9)

Kyle B
Kyle B

Reputation: 2889

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

Upvotes: 17

jhhwilliams
jhhwilliams

Reputation: 2582

Seeing as this question came up while searching for a solution to the same problem in a .Net 5 application I'll just leave this here.

In the docs it is stated that

GetSection never returns null. If a matching section isn't found, an empty IConfigurationSection is returned.

To see if the section is empty, use the Exists method:

var selection = Config.GetSection("section2");
if (!selection.Exists())
{
    throw new System.Exception("section2 does not exist.");
}

Upvotes: 1

Craig
Craig

Reputation: 414

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

Upvotes: 2

dan
dan

Reputation: 1954

I was trying to avoid a XML based solution for this. But seems to be it's the only way to make this happen.

Listing the solution below for the future ref.

[@sr28 and @tchrikch were proposing the same]

if (XDocument
  .Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
  .XPathSelectElement("/*[local-name() = 'configuration']/*[local-name() = 'unity']") == null)

Upvotes: 0

sr28
sr28

Reputation: 5106

Similar to others I think you need to use ConfigurationManager.GetSection(). However, if I read your question correctly are you asking to check if unity exists within a section name="Unity"? If so you will need to do something like:

ConfigurationManager.GetSection("unity/unity");

You can then check against cs if you want or do something similar to what was suggested by RB.

***EDIT***

Ok, how about this, it's a bit more long winded but may work:

ConfigurationSection section = ConfigurationManager.GetSection("unity");
System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument();
xmlData.LoadXml(section);

XmlNode Found = null;

foreach (System.Xml.XmlNode node in xmlData.ChildNodes)         
{             
    if (node.HasChildNodes) 
    {        
        Found = FindNode(node.ChildNodes, "unity"); 
    }          
}

if(Found == null) //do something   

Upvotes: 0

tchrikch
tchrikch

Reputation: 2468

You can open the configuration file with xml reader and navigate to children element named "unity" OR you can implement IConfigurationSectionHandler where inside CreateMethod you can distinguish the incoming node and do the checking if it's line or block

  public class CustomConfigurationSectionHandler : IConfigurationSectionHandler { 
     public object Create(object parent, 
       object configContext, System.Xml.XmlNode section)
           {
                 //check if section is a line , if yes return null
                 if( section ...)
                 { return null; }
                 //otherwise return whatever result you want :)
                 else {  }
           }
   }

the handler needs of course to be registered in the config file so that when you call ConfigurationManager.GetSection("unity") it will be resolved.

Upvotes: 0

Liath
Liath

Reputation: 10191

I believe you can use the ConfigurationManager.GetSection Method.

if(ConfigurationManager.GetSection(sectionName) == null)
{
  // do something
}

Upvotes: -1

elmadj
elmadj

Reputation: 47

You can open your configuration file and try to access the configuration by its name.

CustomSection customSection;

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Create the section entry   
            // in the <configSections> and the  
            // related target section in <configuration>. 
            if (config.Sections["CustomSection"] == null)
            {

enter link description here

Upvotes: -1

RB.
RB.

Reputation: 37192

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");
}

Upvotes: 1

Related Questions