Codality
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 />");
}
}
And that's all. The solution is short so the post is short ;) Any comments? Do not hesitate to write them below.
March 14, 2009 at 8:58 AM
If this modification is made inside ASP.NET Framework, then most likey this is handled with ASPNET account. This account by default has no write permissions for *.config files (please correct me if I'm mistaken). One of the options if to grant ASPNET that kind of access (which is not too secure). And onother option is to write you own WinForms or Console Application which is ran by the current user and which lacks this kind of restriction.
March 14, 2009 at 10:37 AM
And one more thing that is frequently forgotten: if one changes web.config, web application is restarted. It has to be taken into account.
June 26, 2013 at 10:55 AM
So for example if I type an IP address into a textbox, could it then automatically be added to web.config so that the IP will from then on be a permanent part of the web.config?
Sorry, very new to this
June 26, 2013 at 1:30 PM