【问题标题】:app.settings custom configuration issueapp.settings 自定义配置问题
【发布时间】:2014-03-08 03:43:22
【问题描述】:

我在 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]);
    }
}

【问题讨论】:

  • 如果你的文件被命名为“app.settings”,那么这就解释了为什么它不工作。您希望将其命名为“app.config”。
  • 我注意到您没有该类的完全限定名称;这可能是问题所在(虽然不确定,但我会把它放进去)。

标签: c# app-config configsection


【解决方案1】:

我认为您需要添加 section 元素(在您的示例中已注释掉):

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

有关示例,请参阅 sectionGroup Element for configSections

【讨论】:

  • 它被我的用户设置部分挂断了。反正我不需要它,所以我把它去掉了,它现在可以工作了。
  • @Dovey,您应该用解决方案回答您的问题并接受该答案。
猜你喜欢
  • 2011-05-15
  • 2023-01-19
  • 2018-06-21
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多