For some reason, there are things in code that I just cannot remember. One of these things is getting values from configuration – web.config or app.config.
Yes, I know, it is ridiculous. I remember literally hundreds of classes and methods, but a simple, one-line “ConfigurationManager.AppSettings[key]” I have to google. So I just gave up and wrote a wrapper – and to make it a bit more useful, I did a generic version, which can get the configuration value already in a specified type.
So, here is the three-method class, imaginatively named “Config”:
- /// <summary>
- /// Shorthand class for easy access to web.config values
- /// </summary>
- public static class Config
- {
- /// <summary>
- /// Gets the setting as string by key.
- /// Return string.Empty if the key does not exist
- /// </summary>
- /// <param name="key">The key.</param>
- /// <returns></returns>
- public static string GetSettingByKey(string key)
- {
- return ConfigurationManager.AppSettings[key] ?? string.Empty;
- }
- /// <summary>
- /// Generic version of GetSettingByKey().
- /// Returns default(T) if the key does not exist
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key">The key.</param>
- /// <returns></returns>
- public static T GetSettingByKey<T>(string key)
- {
- var value = ConfigurationManager.AppSettings[key];
- return string.IsNullOrWhiteSpace(value) ? default(T) : (T)(object)(value);
- }
- /// <summary>
- /// Returns defaultValue, if the key does not exist.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key">The key.</param>
- /// <param name="defaultValue">The default value.</param>
- /// <returns></returns>
- public static T GetSettingByKey<T>(string key, T defaultValue)
- {
- var value = ConfigurationManager.AppSettings[key];
- return string.IsNullOrWhiteSpace(value) ? defaultValue : (T)(object)(value);
- }
- }
Use it simply Config.GetSettingByKey<int>(“RowCount”) – which would return 0, if the key “RowCount” doesn’t exist. Use Config.GetSettingByKey<int>(“RowCount”, 16) to specify a different default value.
You could also do separate properties for more frequently used configuration values, to avoid typos in string keys:
- public static DateTime MyDateTime
- {
- get { return GetSettingByKey<DateTime>("MyDateTime", DateTime.Now); }
- }
RSS Feed