configSections为自定义节点,增加应用程序可移植性,用于配置文件上传路径,再深入应用可定义工厂方法需要加载创建的类。
1.配置configSections节点
<configSections>
<section name ="MyName" type="LearningConfiguration.NameSectionHandler"/>
</configSections>
<MyName>
<Add key="lu" name="lulu"></Add>
<Add key="lu2" name="66"></Add>
</MyName>
2.定义NameSectionHandler类实现IConfigurationSectionHandler接口
namespace LearningConfiguration
{
public class NameSectionHandler : IConfigurationSectionHandler
{
#region 隐式实现接口
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
Dictionary<string, string> names = new Dictionary<string, string>();
string key = string.Empty;
string name = string.Empty;
//获取配置文件中自定义节点值
foreach (XmlNode childNode in section.ChildNodes)
{
if (childNode.Attributes["key"] != null)
{
key = childNode.Attributes["key"].Value;
if (childNode.Attributes["name"] != null)
{
name = childNode.Attributes["name"].Value;
}
else
{
name = string.Empty;
}
names.Add(key, name);
}
}
return names;
}
#endregion
}
}
3.调用
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> names = ConfigurationManager.GetSection("MyName") as Dictionary<string, string>;
if (names != null)
{
//输出:lulu66
foreach (string key in names.Keys)
{
Response.Write(names[key]);
}
}
}