How To Modify The AppSettings Area in Web.Config 

Every now and then I have an application that’s too simple to require a database back-end, but yet just complex enough that I’d like an administrative user to be able to change a handful of settings on their own.  Here’s some example code on how to make that happen (or see http://ramanisandeep.wordpress.com/2009/04/07/programming-the-webconfig-file-using-c):

First lets read existing configuration and value of the settings element.

protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

System.Configuration.KeyValueConfigurationElement setting = config.AppSettings.Settings["MyValue"];

if (null != setting)
{
// lets do something with the value - displaying it in a textbox is an ides
textboxValue.Text = setting.Value;
}
}
}

We can use web.config file from some other directory if we use its name instead of ‘~’ in WebConfigurationManager.OpenWebConfiguration(“~”) method.

We’ve already read the value and displayed it in textbox
so we are ready to save updated value (or add new settings element if it hasn’t been saved yet).

protected void btnSave_Click(object sender, System.EventArgs e)
{
try
{
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

System.Configuration.KeyValueConfigurationElement setting = config.AppSettings.Settings["MyValue"];

if (null != setting)
{
config.AppSettings.Settings["MyValue"].Value = textboxValue.Text;
}
else
{
config.AppSettings.Settings.Add("MyValue", textboxValue.Text);
}

config.Save();
literalMessage.Text = "New value saved. Application will be restarted automatically.";
}
catch (System.Exception exc)
{
literalMessage.Text = (exc.Message + "<br />" + exc.StackTrace).Replace("\n", "<br />");
}
}