Dovey
Dovey

Reputation: 43

app.settings custom configuration issue

I've attempted my first go round with a custom configuration in app.settings. When I try to call the config I get "Unrecognized configuration section servers". What am I doing wrong?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <sectionGroup name="servers" type="System.Configuration.NameValueSectionHandler"></sectionGroup>
      <sectionGroup name="services" type="System.Configuration.NameValueSectionHandler"></sectionGroup>
      <!--<section name="servers.myServers" type="System.Configuration.NameValueFileSectionHandler" />-->
      <!--<section name="services.myServices" type="System.Configuration.NameValueFileSectionHandler" />-->
      <section name="ServiceMonitor.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <servers>
    <myServers>
      <add key="server1" value="myserverhost"/>
    </myServers>
  </servers>

  <services>
    <myServices>
      <add key="service1" value="spooler"/>
      <add key="service2" value="Apple Mobile Device"/>
    </myServices>
  </services>

  <userSettings>
    <ServiceMonitor.Properties.Settings>
      <setting name="service1" serializeAs="String">
        <value>spooler</value>
      </setting>
      <setting name="service2" serializeAs="String">
        <value>Apple Mobile Device</value>
      </setting>
    </ServiceMonitor.Properties.Settings>
  </userSettings>
  <appSettings>
    <add key="service1" value="spooler"/>
    <add key="service2" value="Apple Mobile Device"/>
  </appSettings>

</configuration>

Here's the C# code I'm using to call the config.

NameValueCollection settings = ConfigurationManager.GetSection("servers/myServers") as NameValueCollection;
if (settings != null)
{
    foreach (string key in settings)
    {
        Console.WriteLine("{0} : {1}", key, settings[key]);
    }
}

Upvotes: 1

Views: 2026

Answers (1)

Randy Levy
Randy Levy

Reputation: 22655

I think you need to add the section element (which is commented out in your example):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="services">
      <section name="myServices" 
        type="System.Configuration.NameValueSectionHandler" />            
    </sectionGroup>
  </configSections>
</configuration>

See sectionGroup Element for configSections for an example.

Upvotes: 1

Related Questions