Click here to Skip to main content
15,884,058 members
Articles / Web Development / ASP.NET
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.00/5 (6 votes)
20 Dec 2012CPOL 58.6K   11   4
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)

C#
/// <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:

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

Very simple, just saves time and typing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Developing software since 1995, starting out with Borland Turbo C++ 3 & Motorolla Assembly.
Eventually learning several different languages such as
Pascal/Delphi,Basic, Visual Basic,FoxPro, ASP, PHP, and Perl.

Currently using the .net framework for most development task.

Hobbies include underwater robotics, and electronics.

George's current language of choice is C#.

Comments and Discussions

 
GeneralMy vote of 1 Pin
sameersprabhu24-Oct-13 17:45
sameersprabhu24-Oct-13 17:45 
GeneralMy vote of 5 Pin
Sandeep Kumar24-Dec-12 5:29
Sandeep Kumar24-Dec-12 5:29 
Elegant solution!
Regards,
Sandeep Kumar.V

GeneralMy vote of 5 Pin
User 786675221-Dec-12 8:29
User 786675221-Dec-12 8:29 
GeneralMy vote of 5 Pin
CodeHawkz20-Dec-12 5:53
CodeHawkz20-Dec-12 5:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.