简体   繁体   English

C# - 错误:集合是只读的

[英]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. 我现在使用的方法是NameValueCollection类,它允许我在我的Web.Config文件中获取我定义的键的值,以显示在适当的位置。 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. ....在使用更新我的配置中列出的值和定义时,有一小部分ActionResult。

    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(); 一旦进入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? 像在Web.Config中更新键和值的替代方法一样?

Firstly, you are creating instance of NameValueCollection and then immediately rewriting it. 首先,您要创建NameValueCollection实例,然后立即重写它。 Secondly you are not using config variable. 其次,您没有使用配置变量。 Thirdly use NameValueCollection.Remove() and Add() methods. 第三,使用NameValueCollection.Remove()Add()方法。 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.) (是的 - 每次重写web.config时,应用程序都会重新启动。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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