Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 892
jerbersoft Avatar asked Apr 06 '09 00:04

jerbersoft


People also ask

What happens when you change the web config file at run time?

the answer i found :- ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.


1 Answers

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.

like image 74
Mitch Wheat Avatar answered Oct 10 '22 03:10

Mitch Wheat