在Webconfig

时间:2016-03-15 05:59:11

标签: c# web-config

我有自定义部分链接,我应该从UI编辑。保存时我无法保存相应密钥的值。它显示 “集合是只读” 错误。请帮我解决这个问题。在此先感谢。

WebConfig:

<sectionGroup name="Menu">
  <section name="Links" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>

C#

NameValueCollection nameValueCol = (NameValueCollection)ConfigurationManager.GetSection("Menu/Links");
var Key = "Key";
var Value = "Value";               
nameValueCol.Set(Key, Value); // Error: collection is read only

所以我尝试删除并添加密钥,但仍显示相同的错误。

nameValueCol.Remove(Key);    // Error: collection is read only
ameValueCol.Add(Key, Value);

1 个答案:

答案 0 :(得分:0)

你能这样试试吗: 在web.config中添加部分并实现自己的部分处理程序

    <sectionGroup name="Menu">
       <section name="Links" type="Solution.Namepsace.KeyHandler"/>
   </sectionGroup>

然后,在您的KeyHandler类中,您可以访问config的值:

public class KeyHandler: ConfigurationSection
{
    #region Configuration Properties
    [ConfigurationProperty("KeyValueCollection")]
    public string KeyValueCollection
    {
        get { return this["KeyValueCollection"] as KeyValueCollection; }
    }
    #endregion
}

类KeyValueCollection看起来像这样:

 [ConfigurationCollection(typeof(KeyValue), AddItemName = "KeyValue")]
public class KeyValueCollection : ConfigurationElementCollection
{ 
        get { return base.BaseGet(index) as KeyValue; }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }

            this.BaseAdd(index, value);
        }
}

最后添加KeyValue类:

public class KeyValue: ConfigurationElement
    {
        #region Constructor(s)
        public KeyValue()
        {
        }

        public KeyValue(string key, string value)
        {
            this.Key= key;
            this.Value= value;
        }
        #endregion

        #region Configuration Properties
        [ConfigurationProperty("Key", IsRequired = true)]
        public string Key
        {
            get { return this["Key"] as string; }
            set { this["Key"] = value; }
        }

        [ConfigurationProperty("Value", IsRequired = true)]
        public string Value
        {
            get { return this["Value"] as string; }
            set { this["Value"] = value; }
        }
        #endregion
    }