简体   繁体   中英

C# - Error: Collection is read-only

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?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM