Read Variable from Web.Config
How can I add and read the value from web.config file?
Solution 1:
Given the following web.config:
<appSettings>
<add key="ClientId" value="127605460617602"/>
<add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
Example usage:
using System.Configuration;
string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
Solution 2:
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
Solution 3:
If you want the basics, you can access the keys via:
string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();
To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:
using System.Configuration;
public static class AppSettingsGet
{
public static string myKey
{
get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
}
public static string imageFolder
{
get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
}
// I also get my connection string from here
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
}
}
Solution 4:
Assuming the key is contained inside the <appSettings>
node:
ConfigurationSettings.AppSettings["theKey"];
As for "writing" - put simply, dont.
The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.
Solution 5:
Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File