代码之家  ›  专栏  ›  技术社区  ›  coder1

将值存储在web.config-appsettings或configSection-哪个更有效?

  •  11
  • coder1  · 技术社区  · 16 年前

    我正在编写一个可以使用几个不同主题的页面,我将在web.config中存储关于每个主题的一些信息。

    创建一个新的分区组并将所有内容存储在一起,还是只将所有内容放在AppSettings中,这样效率更高?

    配置解决方案

    <configSections>
        <sectionGroup name="SchedulerPage">
            <section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
            <section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
        </sectionGroup>
    </configSections>
    <SchedulerPage>
        <Themes>
            <add key="PI" value="PISchedulerForm"/>
            <add key="UB" value="UBSchedulerForm"/>
        </Themes>
    </SchedulerPage>
    

    要访问配置节中的值,我使用以下代码:

        NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
        String SchedulerTheme = themes["UB"];
    

    应用程序设置解决方案

    <appSettings>
        <add key="PITheme" value="PISchedulerForm"/>
        <add key="UBTheme" value="UBSchedulerForm"/>
    </appSettings>
    

    要访问AppSettings中的值,我将使用此代码

        String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
    
    3 回复  |  直到 13 年前
        1
  •  11
  •   Nick Allen    16 年前

    对于更复杂的配置设置,我将使用一个自定义配置部分,该部分清楚地定义了每个部分的角色,例如

    <appMonitoring enabled="true" smtpServer="xxx">
      <alertRecipients>
        <add name="me" email="me@me.com"/>
      </alertRecipient>
    </appMonitoring>
    

    在配置类中,可以使用

    public class MonitoringConfig : ConfigurationSection
    {
      [ConfigurationProperty("smtp", IsRequired = true)]
      public string Smtp
      {
        get { return this["smtp"] as string; }
      }
      public static MonitoringConfig GetConfig()
      {
        return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig
      }
    }
    

    然后,您可以通过以下方式从代码访问配置属性

    string smtp = MonitoringConfig.GetConfig().Smtp;
    
        2
  •  10
  •   to StackOverflow    16 年前

    在效率方面没有可测量的差异。

    如果您只需要名称/值对,那么appsettings就很好了。

    对于任何更复杂的内容,都值得创建一个自定义配置部分。

    对于您提到的示例,我将使用AppSettings。

        3
  •  6
  •   stevemegson    16 年前

    性能上没有区别,因为configurationmanager.appsettings无论如何只调用getsection(“appsettings”)。如果您需要枚举所有键,那么自定义节将比枚举所有AppSettings并在键上查找一些前缀要好,但是如果不需要比NameValueCollection更复杂的内容,则更容易坚持使用AppSettings。

    推荐文章