Elegant way to get appSettings
With the rollout of VS2005 and .NET 2.0 we got a couple new options for getting values out of config files. The most prominent of these is the strongly-typed Settings class generated when you use the VS2005 Settings designer. However, this option is not always available if you have lots of legacy code that uses keys/values in the appSettings section of the config or you’re using a .NET 2.0 Web Site which doesn’t support the VS2005 Settings designer out-of-the box. BTW, how did Microsoft overlook that?
As an ASP.NET developer I’ve seen many different approaches to getting appSettings out of the config file and have yet to find a better technique than this static method:
public static T GetAppSetting<T>(string name, T nullValue) { string str = ConfigurationManager.AppSettings[name]; if (str == null) return nullValue; TypeConverter tc = TypeDescriptor.GetConverter(typeof(T)); return (T)tc.ConvertFromString(str); }
Essentially this wraps the standard ConfigurationManager.AppSettings lookup in a strongly-typed manor with a failsafe if the setting cannot be retrieved. If the setting is found, it is converted into a strongly-typed object by using it’s corresponding type converter to translate it from a string and casting to the generic type. If it is not found, the supplied default value is returned.
<and the geeks rejoice>