Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method for reading config sections

Am trying to implement a generic way for reading sections from a config file. The config file may contain 'standard' sections or 'custom' sections as below.

<configuration> 
<configSections>
    <section name="NoteSettings" type="System.Configuration.NameValueSectionHandler"/>
</configSections>   
<appSettings>
    <add key="AutoStart" value="true"/>
    <add key="Font" value="Verdana"/>
</appSettings>  
<NoteSettings>
    <add key="Height" value="100"/>
    <add key="Width" value="200"/>
</NoteSettings> 

The method that I tried is as follows :

    private string ReadAllSections()
    {
        StringBuilder configSettings = new StringBuilder();

        Configuration configFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

        foreach (ConfigurationSection section in configFile.Sections)
        {
            configSettings.Append(section.SectionInformation.Name);
            configSettings.Append(Environment.NewLine);                

            if (section.GetType() == typeof(DefaultSection))
            {
                NameValueCollection sectionSettings = ConfigurationManager.GetSection(section.SectionInformation.Name) as NameValueCollection;

                if (sectionSettings != null)
                {
                    foreach (string key in sectionSettings)
                    {
                        configSettings.Append(key);
                        configSettings.Append(" : ");
                        configSettings.Append(sectionSettings[key]);
                        configSettings.Append(Environment.NewLine);
                    }
                }
            }

            configSettings.Append(Environment.NewLine);
        }

        return configSettings.ToString();
    }

Assuming that all custom sections will have only KEY-VALUE

  • Is such an implementation possible? And if yes, is there a 'cleaner' and more elegant solution than this one?
  • The above method also reads 'invisible' sections like mscorlib, system.diagnostics. Is this avoidable?
  • System.Data.Dataset returns a dataset which could not be cast to a NameValueCollection. How can this be handled?

Corrections/suggestions welcome.

Thanks.

like image 242
Codex Avatar asked Jan 15 '09 15:01

Codex


People also ask

How to get configuration value in c#?

To retrieve a value for a specified key from the <appSettings> section of the configuration file, use the Get method of the AppSettings property of the ConfigurationManager class. The ConfigurationManager class is in the System. Configuration namespace.

How to access key value from App config in c#?

App.config To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.

What is configuration in C#?

config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.


2 Answers

Since configuration file is XML file, you can use XPath queries for this task:

    Configuration configFile = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    XmlDocument document = new XmlDocument();
    document.Load(configFile.FilePath);
    foreach (XmlNode node in document.SelectNodes("//add"))
    {
        string key = node.SelectSingleNode("@key").Value;
        string value = node.SelectSingleNode("@value").Value;
        Console.WriteLine("{0} = {1}", key, value);
    }

If you need to get all {key, value} pair then you need to define triplets of XPath queries: 1 - main query for selecting nodes with similar structure. 2, 3 - queries for extracting key and value nodes from nodes retrieved by first query. In your case it's enough to have common query for all nodes, but it's easy to maintain support for different custom sections.

like image 141
okutane Avatar answered Oct 01 '22 07:10

okutane


Read your config into a XmlDocument then use XPath to find the elements your looking for?

Something like;

XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/web.config"));

XmlNodeList list = doc.SelectNodes("//configuration/appSettings");

foreach (XmlNode node in list[0].ChildNodes)

...

like image 40
Dead account Avatar answered Oct 01 '22 06:10

Dead account