Access value throughout application in .NET

While developing large applications, the need of global key values arise, that can be used throughout the application.
So, for this purpose we should define the key value in the web.config file and through that specific key can access that value from anywhere in the application.
Also, important thing is that the value can be changed[in web.config] easily without changing the code. Also, environment specific values are also defined here.

Method is defined as below:

In WEB.CONFIG file

Define any number of key values as follows:

<appSettings>
    <add key="key1" value="10"/>
    <add key="key2" value="20"/>
</appSettings>

In Code file[C#.NET]

First Import System.Configuration as follows:

"using System.Configuration;"

Now access the values from their specific keys as follows:

int sum = ConfigurationManager.AppSettings["key1"] + ConfigurationManager.AppSettings["key2"];

In this way you can define any type of values integer, strings etc. and use them accordingly.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>