Simple configuration file for a .NET application

In order to read simple “key-value” configuration file for a .NET application, a class shown below may be used:


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SomeNamespace
{
    public class SimpleConfigurationManager
    {
        public static string GetConfigurationParameterValue(string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            try
            {
                AppSettingsSection c = (AppSettingsSection)config.GetSection("some_section_in_config_file");
                var i = c.ElementInformation;
                return c.Settings[key].Value;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}

The config file, which will be read by the class:

  1. should be stored in the same directory as the executable file
  2. should be named according to this pattern: executable file name + “.config”, for example: MyApp.exe.config
  3. should have following structure:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="some_section_in_config_file" type="System.Configuration.AppSettingsSection" />
  </configSections>

  <some_section_in_config_file>
    <add key="some_key_1" value="1024" />
    <add key="some_key_2" value="www.google.com" />
    <add key="and_some_other_key" value="true" />
  </some_section_in_config_file>

</configuration>
Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: