2016-03-15 41 views
0

我有自定義部分鏈接,我應該從UI進行編輯。保存期間,我無法保存相應密鑰的值。它顯示「收集是隻讀的」錯誤。請幫我解決這個問題。提前致謝。在Webconfig中設置自定義部分NameValueSectionHandler的值

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

回答

0

你可以試試這樣: 在web.config中添加部分和實現自己的區段處理器

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

然後,在你KeyHandler類,你可以訪問值,你的配置:

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 
    }