2011-05-24 33 views
3

我正在嘗試在我的C#.NET控制檯應用程序的app.config文件中創建自定義配置節。這是一些細節存儲有關的一些服務器,例如:app.config中的多個相同的自定義配置

<configSections> 
    <sectionGroup name="serverGroup"> 
    <section name="server" type="RPInstaller.ServerConfig" allowLocation="true" allowDefinition="Everywhere"/> 
    </sectionGroup> 
</configSections> 
<serverGroup> 
    <server> 
    <name>rmso2srvm</name> 
    <isBatchServer>false</isBatchServer> 
    </server> 
    <server> 
    <name>rmsb2srvm</name> 
    <isBatchServer>true</isBatchServer> 
    </server> 
</serverGroup> 

我對服務器的部分定義,像這樣一類:

namespace RPInstaller 
{ 
    public class ServerConfig : ConfigurationSection 
    { 
     [ConfigurationProperty("name", IsRequired=true)] 
     public string Name {...} 

     [ConfigurationProperty("isBatchServer", IsRequired = true)] 
     public bool IsBatchServer {...} 
    } 
} 

當我現在嘗試加載服務器部分我得到一個例外:「節只能在每個配置文件中出現一次」。

我怎麼能夠合法地定義我的app.config文件中的多個服務器節?

回答

2
<confgisections> 
    <section name="server" type="RPInstaller.ServerConfig" allowLocation="true" allowDefinition="Everywhere"/> 
</confgisections> 
<server> 
    <servers> 
    </clear> 
    <add name="rmso2srvm" isBatchServer="false"/> 
    <add name="rmsb2srvm" isBatchServer="true"/> 
    </servers> 
</server> 

是我有一個自定義節前面

VB代碼設置訪問:

Dim cfg As ServerSection = (ConfigurationManager.GetSection("Server"),ServerSection) 
cfg.ServersCollection("nameOfServer").isBatchServer 
+0

真正的答案是這個和VMAtm留下的混合物。我發現以下問題的答案中的鏈接非常有用:[Custom Configuration Sections](http://stackoverflow.com/questions/858618/custom-configuration-sections) – 2011-05-25 07:38:03

0

不能創建在一個web.config中多個服務器的部分。 只有您的自定義部分中有多個元素。 檢查你的web.config - 這似乎是錯誤不是因爲你的代碼。


更新: 您沒有爲您的「服務器」元素定義一個元素 - 只爲配置節。 所以運行時等待像 rmso2srvm部分 假

您應該添加ServerElement : ConfigurationElement類,並將其添加到您的部分類的定義:

namespace RPInstaller 
{ 
    public class ServerConfig : ConfigurationSection 
    { 
    public class ServerElement : ConfigurationElement 
    { 
     [ConfigurationProperty("name", IsRequired=true)] 
     public string Name {...} 
     [ConfigurationProperty("isBatchServer", IsRequired = true)] 
     public bool IsBatchServer {...} 
    } 
    } 
} 

點擊此處瞭解詳情: http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

相關問題