65.9K
CodeProject is changing. Read more.
Home

Quicker Way to Get To ConfigurationManager.AppSettings["Key"]

Dec 20, 2012

CPOL
viewsIcon

59304

Quick Access to appSettings

Introduction 

I dislike having to type out System.Configuration.ConfigurationManager.AppSettings["Foo"] every time I need to reference an application setting in the Web.Config.

You can add System.Configuration to the using section to cut it down to Configuration.ConfigurationManager["Foo"] but that's still too much typing for someone lazy like me. Plus it makes my code look untidy.

Here is a simple extension method to make that job easier (or at least cut down on the typing)

Using the code

Simply place this extension method into a static class in your web application....

(You'll also need to add System.Configuration to the using section)

/// <summary>
/// Returns an application setting based on the passed in string
/// used primarily to cut down on typing
/// </summary>
/// <param name="Key">The name of the key</param>
/// <returns>The value of the app setting in the web.Config
//     or String.Empty if no setting found</returns>
public static string AppSetting(this string Key)
{
  string ret = string.Empty;
  if (System.Configuration.ConfigurationManager.AppSettings[Key] != null)
    ret = ConfigurationManager.AppSettings[Key];
  return ret;
}

and when the time comes to get the value of an application setting key (say to load a label named "Foo") all you need to do is this:

Foo.Text = "SettingName".AppSetting(); 

Very simple, just saves time and typing.