i always use custom config sections

2007-11-09 @ 17:53#

i use .NET/ASP.NET config files to handle lots of details. but instead of just using the default appSettings section in the config file, i whip up custom sections as i need them. this lets me group things easily together. this is especially handy when i am building utility assemblies that will eventually get rolled into other final apps. then each utility can have it's own config section!

here's a quick example. this is the added config section in my app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	
	<configSections>
		<section name="SiteConfig" type="System.Configuration.NameValueSectionHandler" />
	</configSections>
	
	<SiteConfig>
		<add key="save_folder" value="c:\"/>
		<add key="webroot" value="e:\g4\production"/>
		<add key="temproot" value="f:\g4\production"/>
	</SiteConfig>
	
</configuration>

and here's a simple set of functions i add to all my apps that allows me to pull an item from a named config section:

  string GetConfigItem(string section, string key)
  {
      return GetConfigItem(section, key, string.Empty);
  }
  string GetConfigItem(string section, string key, string defaultValue)
  {
      NameValueCollection config_section = (NameValueCollection)ConfigurationManager.GetSection(section);
      return (config_section.Get(key) != null ? config_section.Get(key) : defaultValue);
  }

code