Search code examples
c#configurationconfigurationsection

Loop through the configrationsection to read it's elements using C#


I have a configuration file, something like:

<logonurls>
  <othersettings>
    <setting name="DefaultEnv" serializeAs="String">
      <value>DEV</value>
    </setting>
  </othersettings>
  <urls>      
    <setting name="DEV" serializeAs="String">
      <value>http://login.dev.server.com/Logon.asmx</value>
    </setting>
    <setting name="IDE" serializeAs="String">
      <value>http://login.ide.server.com/Logon.asmx</value>
    </setting>
  </urls>
  <credentials>
    <setting name="LoginUserId" serializeAs="String">
      <value>abc</value>
    </setting>
    <setting name="LoginPassword" serializeAs="String">
      <value>123</value>
    </setting>
  </credentials>    
</logonurls>

How can I read configuration to get the value of keyname passed. Here is the method that I wrote:

private static string GetKeyValue(string keyname)
{
    string rtnvalue = String.Empty;
    try
    {
        ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
        foreach (ConfigurationSection section in sectionGroup.Sections)
        {
            //I want to loop through all the settings element of the section
        }
    }
    catch (Exception e)
    {
    }
    return rtnvalue;
}

config is the Configuration variable that has the data from the config file.


Solution

  • Convert it to proper XML and search within the nodes:

    private static string GetKeyValue(string keyname)
    {
        string rtnValue = String.Empty;
        try
        {
            ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(sectionGroup);
    
            foreach (System.Xml.XmlNode node in doc.ChildNodes)    
            {    
                // I want to loop through all the settings element of the section
                Console.WriteLine(node.Value);
            }
        }
        catch (Exception e)
        {
        }
    
        return rtnValue; 
    }
    

    Just a quick note: if you convert it to XML, you can also use XPath to get the values.

    System.Xml.XmlNode element = doc.SelectSingleNode("/NODE");