C# Example: Reading Configuration Values from App.config File

 

Prepare Configuration File

* Create App.config file if it does not exist.
– For web applications, use Web.config file instead.
* Add a new section, e.g. myConfig, to App.config file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="myConfig" 
        type="System.Configuration.NameValueSectionHandler" />
  </configSections>
 
  <myConfig>
    <add key="key1" value="value1" />
    <add key="key2" value="value2" />
  </myConfig>
</configuration>

Read Configuration Values

* Add System.Configuration to References.

using log4net;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MyProj
{
    public class Properties
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Properties));
 
        private static string key1;
        public static string Key1
        {
            get
            {
                if (string.IsNullOrEmpty(key1))
                {
                    key1 = MyConfigVal("key1");
                }
                return key1;
            }
        }
 
        private static string key2;
        public static string Key2
        {
            get
            {
                if (string.IsNullOrEmpty(key2))
                {
                    key2 = MyConfigVal("key2");
                }
                return key2;
            }
        }
 
        private static string MyConfigVal(string configName)
        {
            string val = MyConfig[configName];
            if (val == null)
            {
                string err = string.Format("{0} not found in App.config.", configName);
                log.Fatal(err);
                throw new ArgumentException(err);
            }
            return val;
        }
 
        private static NameValueCollection myConfig;
        public static NameValueCollection MyConfig
        {
            get
            {
                if (myConfig != null)
                {
                    return myConfig;
                }
 
                myConfig = ConfigurationManager.GetSection(
                    "myConfig") as NameValueCollection;
                if (myConfig == null)
                {
                    throw new ArgumentException(
                        ("myConfig section not found in App.config."));
                }
                return myConfig;
            }
        }
    }
}
This entry was posted in c# and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.