Thursday, May 14, 2015

Split your App.config into Multiple Files

What do you do when any file in your project becomes too big? You break it apart into multiple files!

Did you know that you can split your .NET configuration files into multiple files as well? Here is how...

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="customSection" 
    type="ConfigSectionDemo.CustomConfigurationSection, ConfigSectionDemo" />
  </configSections>
  <appSettings configSource="AppSettings.config" />
  <customSection configSource="CustomSection.config" />
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

AppSettings.config

<appSettings>
  <add key="Hello" value="World"/>
</appSettings>

CustomSection.config

<customSection goodnight="Moon">
</customSection>

Program.cs

using System.Configuration;
using System.Diagnostics;
 
namespace ConfigSectionDemo
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var hello = ConfigurationManager.AppSettings["Hello"];
            Debug.Assert(hello == "World");
 
            var section = (CustomConfigurationSection)ConfigurationManager
                .GetSection("customSection");
            Debug.Assert(section.Goodnight == "Moon");
        }
    }
 
    public class CustomConfigurationSection : ConfigurationSection
    {
        private const string GoodnightLabel = "goodnight";
 
        [ConfigurationProperty(GoodnightLabel)]
        public string Goodnight
        {
            get { return (string)this[GoodnightLabel]; }
            set { this[GoodnightLabel] = value; }
        }
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics