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).
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
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");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With