configSections 配置

在配置文件中添加新的配置节,并用新的方法访问。

配置自定义节:"AppConfig"

用来演示的程序名为MyApp,Namespace也是MyApp

<configSections>
    <section name="AppConfig" type="MyApp.AppConfig, MyApp" />
</configSections>

添加自定义节:"AppConfig"

<AppConfig>
    <add key="ConnectionString" value="this is a ConnectionString" />
    <add key="UserCount" value="199" />
</AppConfig>

在派生类添加方法

我们把所有的配置都映射成相应的静态成员变量,并且是写成只读属性,这样程序通过
类似AppConfig.ConnectionString就可以访问,配置文件中的项目了

using System.Collections.Specialized;
using System.Xml;
public class AppConfig : IConfigurationSectionHandler
{
   static String m_connectionString = String.Empty;
   static Int32 m_userCount = 0;
   public static String ConnectionString
   {
      get
      {
         return m_connectionString;
      }
   }
   public static Int32 UserCount
   {
      get
      {
         return m_userCount;
      }
   }

   static String ReadSetting(NameValueCollection nvc, String key, String defaultValue)
   {
      String theValue = nvc[key];
      if(theValue == String.Empty)
         return defaultValue;
  
      return theValue;
   }

   public object Create(object parent, object configContext, XmlNode section)
   {
      NameValueCollection settings;

      try
      {
         NameValueSectionHandler baseHandler = new NameValueSectionHandler();
         settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);
      }
      catch
      {
         settings = null;
      }

      if ( settings != null )
      {
         m_connectionString = AppConfig.ReadSetting(settings, "ConnectionString", String.Empty);
         m_userCount = Convert.ToInt32(AppConfig.ReadSetting(settings, "UserCount", "0"));
      }
      return settings;
   }
}

设置启动

在Global.asax.cs中的Application_Start中添加以下代码

这样在程序启动后,会读取AppConfig这个Section中的值,系统会调用你自己实现的IConfigurationSectionHandler接口来读取配置

System.Configuration.ConfigurationSettings.GetConfig("AppConfig");