Reputation: 301
Im trying to creating a custom settings system for an administration and moderator panel that changes things like the site name, description, and so on. The method I'm using now is the NameValueCollection class that allows me to get the values of my defined keys within my Web.Config file to display in their proper places. My problem is, when it comes down to changing these values, I get Collection is read-only..... Heres a small snippet of the ActionResult in using to update the values and the definitions listed in my config.
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
NameValueCollection settings = new NameValueCollection();
settings = (NameValueCollection)ConfigurationManager.GetSection("settings");
settings.Set("siteName", SiteName);
settings.Set("siteDesc", SiteDesc);
return RedirectToAction("Index");
<section name="settings" type="System.Configuration.NameValueFileSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<settings>
<add key="siteName" value="Gizmo" />
<add key="siteDesc" value="Welcome to a Gizmo Powered Website." />
</settings>
Once it goes to settings.Set(); thats where the error begins. Is there anyway I get around this? Like an alternative way of updating the keys and values in my Web.Config?
Upvotes: 4
Views: 16388
Reputation: 7696
Firstly, you are creating instance of NameValueCollection
and then immediately rewriting it. Secondly you are not using config variable. Thirdly use NameValueCollection.Remove()
and Add()
methods. It should do the trick...
See following example (it's very very similar to what you want to do)
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
string key = "asd";
var origValue = config.AppSettings.Settings[key];
string newValue = origValue.Value + "changed";
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, newValue);
(And yes - every time you rewrite the web.config the application gets restarted.)
Upvotes: 6