How do you modify the web.config appSettings at runtime?
Asked Answered
G

7

88

I am confused on how to modify the web.config appSettings values at runtime. For example, I have this appSettings section:

<appSettings>
  <add key="productspagedesc" value="TODO: Edit this default message" />
  <add key="servicespagedesc" value="TODO: Edit this default message" />
  <add key="contactspagedesc" value="TODO: Edit this default message" />
  <add key="aboutpagedesc" value="TODO: Edit this default message" />
  <add key="homepagedesc" value="TODO: Edit this default message" />
 </appSettings>

Let's say, I want to modify the "homepagedesc" key at runtime. I tried ConfigurationManager and WebConfigurationManager static classes, but the settings are "read-only". How do I modify appSettings values at runtime?

UPDATE: Ok, so here I am 5 years later. I would like to point out that experience has told me, we should not put any configuration that intentionally is editable at runtime in the web.config file but instead we should put it in a separate XML file as what one of the users commented below. This will not require any of edit of web.config file to restart the App which will result with angry users calling you.

Grubstake answered 6/4, 2009 at 0:14 Comment(3)
Here is a good link that nicely explain about modifying the web.config at runtime and its impact in application. http://aspdotnethacker.blogspot.com/2010/05/modify-webconfig-file-at-runtime.htmlRazid
@Razid the link you provided is no longer validYorgo
It only takes a few seconds to find the archived version!Allrud
D
85

You need to use WebConfigurationManager.OpenWebConfiguration(): For Example:

Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()

I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.

Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).

Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.

Desexualize answered 6/4, 2009 at 0:26 Comment(2)
Thanks for the response Mitch. You answered my question. What I did was I run VS 2008 as Administrator and everything was doing fine.Grubstake
Perhaps obvious to others (wasn't to me), this answer, as well as Amin's which is functionally the same, actually overwrites your physical web.config file, doesn't just override the setting in memory for the specific running instance.Bikales
P
26

Changing the web.config generally causes an application restart.

If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.

Perspex answered 6/4, 2009 at 0:22 Comment(5)
Hi, thanks for the response. But there is this "Configuration" class that has a "Save" function. Do you really have to restart the app for the new settings to be active?Grubstake
Changing the web.config automatically triggers an application restart.Aldershot
Changing web.config dynamically should not be recommended. I would prefer to store the value in a (xml)file.Nosing
can someone explain why restarting application is bad and many recommend to move the attribute to a different file?Lafayette
@Lafayette - I know it's a few months since, but just in case - restarting the app will mean anyone logged in to your app at the point of restart will get automatically logged out and most likely encounter an error. (various scenarios such as web farms notwithstanding...). angry users contact support, support contacts you etc etc etc...Schweiz
U
24

And if you want to avoid the restart of the application, you can move out the appSettings section:

<appSettings configSource="Config\appSettings.config"/>

to a separate file. And in combination with ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

Underlinen answered 11/12, 2014 at 13:32 Comment(0)
P
22

2012 This is a better solution for this scenario (tested With Visual Studio 2008):

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();

Update 2018 =>
Tested in vs 2015 - Asp.net MVC5

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();

if u need to checking element exist, use this code:

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();
Pinta answered 8/8, 2012 at 6:31 Comment(5)
Could you elaborate a bit why it's better? I know configSection stuff sometimes is a bit tricky.Claudioclaudius
This code is smaller and more understandable! At least for me.Pinta
Oh, it's because of personal taste then, I actually thought it was logically different somehow. I highly disagree with you in this case though for a bunch of reasons actually: first because you have to specify the same key twice, second because what you are doing is semantically different than what is actually needed ('update' vs 'remove->add') and third because the code is actually longer (not sure why you thing otherwise here) and open to mistakes. Also, what if for some reason your code fails between the calls? Your application is broken from there on I think.Claudioclaudius
This code erases any comment sibling to MyVariable.Periotic
Yes, exactly ! This code code be rewritten all variables, but it works . but i not Recommend to used it, when u used comment code. Thank you.Pinta
D
17

I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.

I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.

The project goals were very simple;

  1. get ASP.NET to communicate with ZooKeeper
  2. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.

Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;

ConfigurationManager.AppSettings.Add(key_name, data_value)

That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.

After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.

With a little trial and error, I found the following code would do exactly what I wanted;

ConfigurationManager.AppSettings.Set(key_name, data_value)

Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.

In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;

appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True

With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.

This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.

I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

Deposition answered 6/6, 2016 at 12:46 Comment(0)
T
6

Who likes directly to the point,

In your Config

    <appSettings>

    <add key="Conf_id" value="71" />

  </appSettings>

in your code(c#)

///SET
    ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
      ///GET              
    string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();
Turgeon answered 16/2, 2017 at 12:34 Comment(1)
to the pint solution. I checked in WebAPI, working in production without any IIS Security changesThorley
W
1

Try This:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}
Woll answered 27/6, 2017 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.