【问题标题】:Multiple identical custom config sctions in app.configapp.config 中的多个相同的自定义配置部分
【发布时间】:2011-05-24 16:34:04
【问题描述】:

我正在尝试在我的 C# .NET 控制台应用程序的 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 文件中合法地定义多个服务器部分?

【问题讨论】:

    标签: .net app-config console-application custom-sections


    【解决方案1】:
    <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
    

    【讨论】:

    【解决方案2】:

    您不能在一个 web.config 中创建多个服务器部分。 您的自定义部分中只有多个元素。 检查您的 web.config - 似乎错误不是由您的代码引起的。


    更新: 您没有为“服务器”元素定义元素 - 仅用于 ConfigurationSection。 所以运行时等待部分像 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

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 2011-10-02
      • 2011-11-04
      • 2015-07-05
      • 2011-05-25
      • 2013-05-19
      • 1970-01-01
      • 2011-12-10
      • 2010-10-20
      相关资源
      最近更新 更多