40

I want to create a variable in web.config file and to use that variable in web forms. How can I achieve this??

Chakri
  • 770
  • 2
  • 7
  • 24

3 Answers3

75

in web.config:

<appSettings>
   <add key="message" value="Hello, World!" />
</appSettings> 

in cs:

string str = ConfigurationManager.AppSettings["message"].ToString();
DmitryK
  • 1,333
  • 1
  • 11
  • 18
  • 1
    Please refer to this link http://stackoverflow.com/questions/1274852/the-name-configurationmanager-does-not-exist-in-the-current-context if you have issues with ConfigurationManager not working. – John M Jul 04 '16 at 14:17
  • 1
    You forgot to mention to add the class in the code (`using System.Configuration`) – Malcolm Salvador Feb 03 '17 at 01:33
16

You may try like this:

<appSettings>
   <add key="id" value="12762"/>
   <add key ="url" value="http://localhost:10982/Redirect.aspx"/>
</appSettings>

Then you can use

using System.Configuration;

and use it like this:

string id=ConfigurationManager.AppSettings["Id"].ToString();
string url=ConfigurationManager.AppSettings["Url"].ToString();
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
4

FYI: The accepted answers for accessing web.config data are considered "Obsolete" now and should be replaced with:

Example:

in web.config:

<appSettings>
   <add key="message" value="Hello, World!" />
</appSettings>

in c#:

ConfigurationManager.AppSettings["message"]

Reference: ConfigurationSettings.AppSettings is obsolete, warning

Community
  • 1
  • 1
AndyRBlank
  • 106
  • 8