配置文件configSections节点使用实例      。

来源:互联网 发布:尤克里里调音软件 安卓 编辑:程序博客网 时间:2024/05/17 06:22

configSections为自定义节点,增加应用程序可移植性,用于配置文件上传路径,再深入应用可定义工厂方法需要加载创建的类。

1.配置configSections节点

[html] view plain copy
print?
  1. <configSections>  
  2.     <section name ="MyName" type="LearningConfiguration.NameSectionHandler"/>  
  3. </configSections>  
  4. <MyName>  
  5.     <Add key="lu" name="lulu"></Add>  
  6.     <Add key="lu2" name="66"></Add>  
  7. </MyName>  


2.定义NameSectionHandler类实现IConfigurationSectionHandler接口

[csharp] view plain copy
print?
  1. namespace LearningConfiguration  
  2. {  
  3.     public class NameSectionHandler : IConfigurationSectionHandler  
  4.     {  
  5.         #region 隐式实现接口  
  6.         public object Create(object parent, object configContext, System.Xml.XmlNode section)  
  7.         {  
  8.             Dictionary<stringstring> names = new Dictionary<stringstring>();  
  9.             string key = string.Empty;  
  10.             string name = string.Empty;  
  11.   
  12.             //获取配置文件中自定义节点值  
  13.             foreach (XmlNode childNode in section.ChildNodes)  
  14.             {  
  15.                 if (childNode.Attributes["key"] != null)  
  16.                 {  
  17.                     key = childNode.Attributes["key"].Value;  
  18.   
  19.                     if (childNode.Attributes["name"] != null)  
  20.                     {  
  21.                         name = childNode.Attributes["name"].Value;  
  22.                     }  
  23.                     else  
  24.                     {  
  25.                         name = string.Empty;  
  26.                     }  
  27.   
  28.                     names.Add(key, name);  
  29.                 }  
  30.             }  
  31.   
  32.             return names;  
  33.         }  
  34.         #endregion  
  35.     }  
  36. }  

 

3.调用

[csharp] view plain copy
print?
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Dictionary<stringstring> names = ConfigurationManager.GetSection("MyName"as Dictionary<stringstring>;  
  4.     if (names != null)  
  5.     {  
  6.             //输出:lulu66  
  7.         foreach (string key in names.Keys)  
  8.         {  
  9.             Response.Write(names[key]);  
  10.         }  
  11.     }  
  12. }  

0 0
原创粉丝点击