Sunday, October 8, 2017

Read .NET configuration files using NameValueSectionHandler and AppSettingsSection Types

Hello all,
I've read from a tutorial NameValueCollection and .NET Configuration Files which targets .NET 1.0/1.1 on how to read config files using type NameValueSectionHandler. I intend to explore more on applying this concept to recent versions of .NET frameworks. Upon doing some diggings, I came up with two options. First is using NameValueSectionHandler type and the other one is AppSettingsSections. To begin with, I have this App.config file with XML elements scriptsfiles and docfiles all registered in configSections.
<?xml version="1.0" encoding="utf-8" ?>
    <section name="scriptfiles" type="System.Configuration.NameValueSectionHandler"/>
    <section name="docfiles" type="System.Configuration.AppSettingsSection"/>
    <add key="C:\batchfiles\2017" value="*.bat" />
    <add key="C:\vbs\2017" value="*.vbs" />
    <add key="C:\applicants\2017" value="*.doc" />
    <add key="C:\officemanuals\2017" value="*.pdf" />
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
If you noticed, each sections are declared with different types specifically NameValueSectionHandler and AppSettingsSection with similar node structures. To read the element with type NameValueSectionHandler we use the ConfigurationManager.GetSection() method.
C# Code
private static void ReadNameValueSectionHandler()
 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
 NameValueCollection scriptFiles = (NameValueCollection)ConfigurationManager.GetSection(config.GetSection("scriptfiles").SectionInformation.SectionName);
 foreach (var item in scriptFiles.AllKeys)
  Console.WriteLine(String.Format("Key:{0}, value:{1}", item, scriptFiles[item]));
For the element with AppSettingsSection type we simply cast the ConfigurationSection object to AppSettingsSection.
C# Code
private static void ReadAppSettingsSection()
 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 ConfigurationSection section = config.GetSection("docfiles");
 var scriptSettings = ((AppSettingsSection)section).Settings;    

 foreach (var item in scriptSettings.AllKeys)
  Console.WriteLine(String.Format("Key:{0}, value:{1}", item, scriptSettings[item].Value));


Post a Comment