获取配置文件中configSections的配置信息!

configSections的作用很多!我就不多举了。

首先要注意的一点是!configSections关联的类型在一个进程内只实例化一次,

1、配置文件Web.config

 1<configuration>
 2<configsections>
 3<section name="xinyulou" type="Config.ConfigurationHandler, Config"></section>
 4</configsections>
 5<xinyulou>
 6<add name="Region" value="心雨楼"></add>
 7</xinyulou>
 8<system.web>
 9<compilation debug="true" defaultlanguage="c#"></compilation>
10<customerrors mode="RemoteOnly"></customerrors>
11<authentication mode="Windows"></authentication>
12<authorization>
13<allow users="*"></allow> <!-- <sectionGroup name="xinyulou"> 允许所有用户 -->
14</authorization>
15<trace enabled="false" localonly="true" pageoutput="false" requestlimit="10" tracemode="SortByTime"></trace>
16<sessionstate cookieless="false" mode="InProc" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=yes" stateconnectionstring="tcpip=127.0.0.1:42424" timeout="20"></sessionstate>
17<globalization requestencoding="utf-8" responseencoding="utf-8"></globalization>
18</system.web>
19</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的威力很强大。有很多种用法与应用!这里就不再举例了,有问题可与我联系。或在恢复中提出来!

Published At
Categories with Web编程
Tagged with
comments powered by Disqus