3
votes

I'm attempting to create a custom config section in the app.config file of my C# .NET console application. It's to store some details about some servers, like so:

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

I have a class defined for the server section like so:

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

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

When I now attempt to load the server sections I get an exception: "Sections must only appear once per config file".

How would I be able to legally define multiple server sections within my app.config file?

2

2 Answers

2
votes
<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>

Is how I have set up a custom section previously

VB Code to access:

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

You can't create multiple server sections in the one web.config. Only multiple elements in your custom sections. Check your web.config - it seems that error is caused not because of your code.


Update: You didn't define a element for your "server" element - only for ConfigurationSection. So the runtime awaits section like rmso2srvm false

You should add the ServerElement : ConfigurationElement class, and add it to the definition of your section class:

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

More information here: http://msdn.microsoft.com/en-us/library/2tw134k3.aspx