ConfigurationManager.GetSection()方法的使用
GetSection方法读取的是configSections节点,这个节点在web.config配置文件中,它比较特殊,必须放 置于首节点,也就是说,在它之前不能有其它类型的节点。configSections子节点有section和sectionGroup,后者是前者的集 合节点:
<configSections> <section name="CustomConfig" type="ConsoleApplication1.CustomConfig, ConsoleApplication1"/> </configSections> <CustomConfig> <Person Name="AAA" Sex="M"/> <Person Name="BBB" Sex="F"/> </CustomConfig>
通过对ConfigurationManager.GetSection(...)方法的调用,如果某个类继承IConfigurationSectionHandler接口,那么会触发此接口的Create方法,这样我们就可以做一些事了。
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace ConsoleApplication1 { public class CustomConfig : IConfigurationSectionHandler { public class LoveConfig { public string Name { get; set; } public string Sex { get; set; } } public object Create(object parent, object configContext, XmlNode section) { if (section == null) return null; List<LoveConfig> list = new List<LoveConfig>(); foreach (XmlNode node in section.ChildNodes) { if (node.Name.ToLower() == "person") { var app = new LoveConfig(); app.Name = node.Attributes["Name"].Value; app.Sex = node.Attributes["Sex"].Value; list.Add(app); } } return list; } } }
调用:
static void Main(string[] args) { var lst = (List<CustomConfig.LoveConfig>)ConfigurationManager.GetSection("CustomConfig"); var lst2 = ConfigurationManager.GetSection("CustomConfig"); foreach (var item in lst) { Console.WriteLine(item.Name + item.Sex); } Console.WriteLine("Task End !"); Console.ReadLine(); }