configSections的作用很多!我就不多举了。
首先要注意的一点是!configSections关联的类型在一个进程内只实例化一次,
1、配置文件Web.config
<?XML version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="xinyulou" type="Config.ConfigurationHandler, Config" />
</configSections>
<xinyulou>
<add name="Region" value = "心雨楼" />
</xinyulou>
<system.web>
<compilation defaultLanguage="c#" debug="true" />
<customErrors mode="RemoteOnly" />
<authentication mode="Windows" />
<authorization>
<allow users="*" /> <!-- <sectionGroup name="xinyulou"> 允许所有用户 -->
</authorization>
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false" timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
</configuration>
2、两个重要的类
using System;
using System.Configuration;
using System.Collections;
using System.XML;
namespace Config
{
public class Configuration
{
private Hashtable m_MyRegionConfig = new Hashtable();
public Hashtable MyRegionConfig
{
get {return m_MyRegionConfig;}
}
public static Configuration GetConfig()
{
return (Configuration) ConfigurationSettings.GetConfig("xinyulou");
}
internal void LoadValuesFromConfigurationXML(XMLNode node)
{
foreach (XMLNode child in node.ChildNodes)
{
m_MyRegionConfig.Add(child.Attributes["name"].Value,child.Attributes["value"].Value);
}
}
}
internal class ConfigurationHandler : IConfigurationSectionHandler
{
public virtual object Create(Object parent, Object context, XMLNode node)
{
Configuration config = new Configuration();
config.LoadValuesFromConfigurationXML(node);
return config;
}
}
}
3、示例在ASPx中用!
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write(Configuration.GetConfig().MyRegionConfig["Region"].ToString());
}
configSections的威力很强大。有很多种用法与应用!这里就不再举例了,有问题可与我联系。或在恢复中提出来!