2013-01-03 31 views
1

我想提出,看起來像添加多個自定義節到應用程序配置C#?

<configuration> 

<SQLconneciton> 
    <add key=name/> 
    <add key= otherStuff/> 
</SQLconnection> 
<PacConnection> 
    <add key=name/> 
    <add key= otherStuff/> 
</PacConnection> 

</configuration> 

我看過很多例子,人們做出ONE定製部分,並添加東西一個app.config,我需要允許用戶添加多個部分,閱讀,刪除。我並不需要花哨的元素,只需簡單的添加和鍵值。部分組值得使用還是有一些容易丟失的東西?

回答

1

當然 - 真的沒有什麼能阻止你創建儘可能多的自定義配置部分!

嘗試這樣:

<?xml version="1.0"?> 
<configuration> 
    <!-- define the config sections (and possibly section groups) you want in your config file --> 
    <configSections> 
    <section name="SqlConnection" type="System.Configuration.NameValueSectionHandler"/> 
    <section name="PacConnection" type="System.Configuration.NameValueSectionHandler"/> 
    </configSections> 
    <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 
    </startup> 
    <!-- "implement" those config sections as defined above --> 
    <SqlConnection> 
    <add key="abc" value="123" /> 
    </SqlConnection> 
    <PacConnection> 
    <add key="abc" value="234" /> 
    </PacConnection> 
</configuration> 

System.Configuration.NameValueSectionHandler是使用含有<add key="...." value="....." />條目(如<appSettings>)一個配置節的默認類型。

要得到的值,只要使用這樣的事情:

NameValueCollection sqlConnConfig = ConfigurationManager.GetSection("SqlConnection") as NameValueCollection; 
string valueForAbc = sqlConnConfig["abc"]; 

而且你完全可以搭配,如果你」匹配現有區段處理器類型由.NET以及定義自己的自定義配置部分,我自己定義了一些 - 只需使用你需要的任何東西!

相關問題