Here is a quick way to create a ConfigSection Handler for reading Hierarchical configs. For e.g. suppose you need to read a config file which has the following structure:
1: <MainConfig>
2: <Company>MySpace</Company>
3: <SubConfig>
4: <ID>23</ID>
5: <Name>Rohit</Name>
6: <LastName>Gupta</LastName>
7: </SubConfig>
8: </MainConfig>
For this you would create the 2 classes, one for the Parent Config and another for the child config like this:
1: [XmlRoot("MainConfig")]
2: public class MainConfig
3: {
4: private static readonly MainConfig instance = (MainConfig)ConfigurationManager.GetSection("MainConfig");
5: public static MainConfig GetInstance()
6: {
7: if (instance == null)
8: throw new ConfigurationErrorsException(
9: "Unable to locate or deserialize the 'SearchRecommendationsConfiguration' section.");
10:
11: return instance;
12: }
13:
14: public string Company { get; set; }
15:
16: public SubConfig FriendsConfig { get; set; }
17: }
18:
19: [XmlRoot("SubConfig")]
20: public class SubConfig
21: {
22: public int ID { get; set; }
23: public string Name { get; set; }
24: public string LastName { get; set; }
25: }
Then you would create a configsectionHandler class which reads the config from the .config file:
1: public class MainConfigSectionHandler : IConfigurationSectionHandler
2: {
3: #region IConfigurationSectionHandler Members
4:
5: public object Create(object parent, object configContext, System.Xml.XmlNode section)
6: {
7: MainConfig typedConfig = GetConfig<MainConfig>(section);
8:
9: if (typedConfig != null)
10: {
11: #region Get Sub Configs
12: foreach (XmlNode node in section.ChildNodes)
13: {
14: switch (node.Name)
15: {
16: case "SubConfig":
17: SubConfig friendsConfig = GetConfig<SubConfig>(node);
18: typedConfig.FriendsConfig = friendsConfig;
19: break;
20: default:
21: break;
22: }
23: }
24: #endregion
25: }
26:
27:
28: return typedConfig;
29: }
30:
31: public T GetConfig<T>(System.Xml.XmlNode section) where T : class
32: {
33: T sourcedObject = default(T);
34: Type t = typeof(T);
35: XmlSerializer ser = new XmlSerializer(typeof(T));
36: sourcedObject = ser.Deserialize(new XmlNodeReader(section)) as T;
37: return sourcedObject;
38: }
39:
40: #endregion
41:
42: }
After this you would add a entry in the app.config for this configsection Handler as the following:
1: <configSections>
2: <section name="MainConfig" type="App.MainConfigSectionHandler,App" />
3: </configSections>
Finally to read this config, you would write the following:
1: MainConfig config = MainConfig.GetInstance();
2: Console.WriteLine(config.Company);
3: Console.WriteLine(config.FriendsConfig.ID);
4: Console.WriteLine(config.FriendsConfig.LastName);
5: Console.WriteLine(config.FriendsConfig.Name);