Home
Manage Your Code
Snippet: ConfigReader Helper Class (C#)
Title: ConfigReader Helper Class Language: C#
Description: This class is a singleton class designed to help read sections from a configuration file that is NOT the app.config or web.config file. I used it for a console application that was passed a configuration file name on the command line. Views: 320
Author: Michael Wood Date Added: 2/15/2007
Copy Code  
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Configuration;
5
6namespace mvwood
7{
8    /// <summary>
9    /// This ConfigurationReader class is used so that the hosting application and any components
10    /// can read their configuration settings without having to write the code to do so or know what the configuration
11    /// file name is.  This is for reading configuration from a file that is NOT the web.config or app.config.
12    /// </summary>
13    public class ConfigurationReader
14    {
15        private static ConfigurationReader _configReader; //Used to store the single instance of the ConfigurationReader class.
16        private static object _configLockObject = new object(); //Used for thread safety to create the _configReader instance.
17        private Configuration _processConfiguration; //Used to store the configuration read from the fil.
18
19        /// <summary>
20        /// This protected constructor is called when the ConfigurationReader class is intialized by the Intialize
21        /// method call.  It reads the configuration file into memory and stores the Configuration object internally.
22        /// </summary>
23        /// <param name="processConfigurationFile">The full path and filename of the configuration file to use.</param>
24        protected ConfigurationReader(string processConfigurationFile)
25        {
26            ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
27            configFile.ExeConfigFilename = processConfigurationFile;
28            _processConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
29        }
30
31        /// <summary>
32        /// This method is called to intialize the ConfigurationReader class.  It should only be called once to
33        /// inform the ConfigurationReader what config file to use.  After that time the static Current method should
34        /// be used to get the stored configuration to return the configuration sections.
35        /// </summary>
36        /// <param name="processConfigurationFile">The full path and filename of the process configuration file to
37        /// use.</param>
38        /// <exception cref="InvalidOperationException">This exception type will be thrown if the ConfigurationReader
39        /// has already been intialized with a configuration file.</exception>
40        public static void Initialize(string processConfigurationFile)
41        {
42            if (_configReader == null)
43            {
44                lock (_configLockObject)
45                {
46                    if (_configReader == null)
47                    {
48                        _configReader = new ConfigurationReader(processConfigurationFile);
49                    }
50                }
51            }
52            else
53            {
54                throw new InvalidOperationException(String.Format("The ConfigurationReader is already configured to use {0}.", _configReader._processConfiguration.FilePath));
55            }
56        }
57
58        /// <summary>
59        /// Returns a reference to currently configured ConfigurationReader object.  The Intialize method must
60        /// have already been called in order to retrieve a valid instance.
61        /// </summary>
62        /// <returns>An instance of the ConfigurationReader class that has been initialized.</returns>
63        /// <exception cref="InvalidOperationExcpetion">This exception type will be thrown if the Intialize method has not been called.</exception>
64        public static ConfigurationReader Current()
65        {
66            if (_configReader == null)
67            {
68                throw new InvalidOperationException("The Intialize static method must be called on the ConfigurationReader object prior to the object being available.");
69            }
70            else
71            {
72                return _configReader;
73            }
74        }
75
76        /// <summary>
77        /// This method returns a strongly typed instance of a class stored in the configuration file.  The type
78        /// must inherit from ConfigurationSection.  If the section name does not exist in the file then a null is
79        /// returned.
80        /// </summary>
81        /// <typeparam name="T">A type that inherits from ConfigurationSection.</typeparam>
82        /// <param name="sectionname">The configuration section name type T is stored under in the configuration file.</param>
83        /// <returns>A class of type T that inherits from ConfigurationSection.</returns>
84        public T GetSection<T>(string sectionname) where T:ConfigurationSection
85        {
86            return (T)_processConfiguration.GetSection(sectionname);
87        }
88
89    }
90}
91
Usage
//Somewhere in your code you'll initialize the component which sets the singleton instance.
string mappedConfigFile = Path.Combine(Environment.CurrentDirectory, "MyOtherConfigFile.config");
ConfigurationReader.Initialize(mappedConfigFile);

//Anywhere in your code downchain within the same process you can get a strongly typed instance
//of a object within the configuration file (that derives from ConfigurationSection by doing this:

MyConfigObject _settings = ConfigurationReader.Current().GetSection("MyConfigObjectSettings");
//Note: MyConfigObjectSettings is the string section name of the section within the config file.


Notes
You must call the static Intialize on the class with the configuration file path and filename before you attempt to use the Current method. If you fail to initalize the component and InvalidOperationException will be thrown. Likewise, if you attempt to call Intialize multiple times an InvalidOperationException will be thrown.