2009-06-15 19 views
5

私は自分のカスタム構成セクションを持っていますが、その内部に単純なキー/値を持つ新しい要素を作成したいと考えています。今は動作していますが、このような簡単な作業のためにかなりのコードが必要です。物事を改善する方法はありますか?基本的なカスタム構成セクションを定義する方法は?

以下は、私の設定とカスタム設定クラスを削除したものです。

web.configファイル

<myRootNode> 
    <myNode> 
     <add key="a" value="" /> 
     <add key="b" value="" /> 
     <add key="c" value="" /> 
     ... 
    </myNode> 
    ...any other nodes 
</myRootNode> 

カスタム構成クラス

public class MyRootNode : ConfigurationSection 
{ 
    [ConfigurationProperty("myNode")] 
    public MyNodeElement MyNode 
    { 
     get { return (MyNodeElement)this["myNode"]; } 
    } 
} 

[ConfigurationCollection(typeof(BaseElement), AddItemName = "add")] 
public class MyNodeElement : ConfigurationElementCollection 
{ 
    protected override ConfigurationElement CreateNewElement() 
    { 
     return new BaseElement(); 
    } 

    protected override object GetElementKey(ConfigurationElement element) 
    { 
     return ((BaseElement)element).Key; 
    } 

    public BaseElement this[int index] 
    { 
     get { return this.BaseGet(index) as BaseElement; } 
    } 
} 

public class BaseElement : ConfigurationElement 
{ 
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)] 
    public string Key 
    { 
     get { return this["key"].ToString(); } 
    } 

    [ConfigurationProperty("value", IsRequired = true)] 
    public string Value 
    { 
     get { return this["value"].ToString(); } 
    } 
} 
+0

この記事を追加:[C#のカスタム構成設定セクションの作成](http://www.codearsenal.net/2012/10/writing-custom-configuration-section-in-csharp.html) –

答えて

9

私は推測する。このような何か:

<configSections> 
     <section name="validationXsds" type="System.Configuration.DictionarySectionHandler, System" /> 
    </configSections> 


    <validationXsds> 
    <add key="http://schemas.xmlsoap.org/soap/envelope/" value="http://dev.ei.directv.com/schemas/xmlsoap/envelope.xsd"/> 
    <add key="http://schemas.xmlsoap.org/soap/encoding/" value="http://dev.ei.directv.com/schemas/xmlsoap/encoding.xsd"/> 
    <add key="http://ei.directv.com/schemas/envelope/v3_0" value="http://dev.ei.directv.com/schemas/envelope/v3.0/Envelope.xsd"/> 
    </validationXsds> 

IDictionary xsds = (IDictionary)WebConfigurationManager.GetSection("validationXsds"); 

を更新:.NET 4.0で、私は

を使用しています
type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" 
6

これを手動で行うには、あまりにも多くの労力が必要です。 Visual StudioでConfiguration Section Designerアドインを使用してセクションを作成させることができます。

+0

Visual Stuiod 2008が必要ですまたはそれ以上である。 – David

+3

実際には、VS 2010はまだサポートされていません。 :o( – Boydski

+0

アルファコードとChromeは悪意のあると思っています。 – stuartdotnet