проблема пользовательской конфигурации app.settings - PullRequest
1 голос
/ 04 сентября 2011

Я попытался сделать первый шаг с пользовательской конфигурацией в app.settings. Когда я пытаюсь вызвать конфигурацию, я получаю «Нераспознанные серверы раздела конфигурации». Что я делаю не так?

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

Вот код C #, который я использую для вызова конфигурации.

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

1 Ответ

1 голос
/ 04 сентября 2011

Я думаю, вам нужно добавить элемент section (который закомментирован в вашем примере):

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

См. Элемент sectionGroup для configSections для примера.

...