有时候,我们需要在应用程序配置文件(app.config)或网站配置文件(web.config)中自定义一些信息,靠appSetting和connectionString不能满足需求。
首先在配置文件中添加configSections节,说明自定义配置节的名称,并制定读取方式(用什么处理程序来读取),这里我演示自定义处理程序读取,自定义处理程序必须实现IConfigurationSectionHandler接口
1.定义实体类Student
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication {
- public enum Gender {
- Female,
- Male
- }
- public enum Grade{
- G1,
- G2,
- G3
- }
- public class Student {
- public string Name { get; set; }
- public int Age { get; set; }
- public Gender Gender { get; set; }
- public Grade Grade { get; set; }
- public string Hobby { get; set; }
- public override string ToString() {
- return string.Format("我是{0}{1},今年{2}岁,我喜欢{3}。",
- Name,
- Gender==Gender.Male?"男生":"女生",
- Age,
- Hobby);
- }
- }
- }
2.定义自定义处理程序StudentSectionHandler来创建对象
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- using System.Xml;
- namespace ConsoleApplication {
- public class StudentSectionHandler : IConfigurationSectionHandler {
- public object Create(object parent, object configContext, XmlNode section) {
- List<Student> stuList = new List<Student>();
- try {
- foreach(XmlNode stuNode in section.ChildNodes){
- Student stu = new Student();
- foreach (XmlNode node in stuNode.ChildNodes) {
- switch (node.Name) {
- case "Name": stu.Name = node.InnerText; break;
- case "Age": stu.Age = Convert.ToInt32(node.InnerText); break;
- case "Gender": stu.Gender = (Gender)Enum.Parse(typeof(Gender), node.InnerText); break;
- case "Grade": stu.Grade = (Grade)Enum.Parse(typeof(Grade), node.InnerText); break;
- case "Hobby": stu.Hobby = node.InnerText; break;
- }
- }
- stuList.Add(stu);
- }
- } catch (Exception ex) {
- throw ex;
- }
- return stuList;
- }
- }
- }
3.配置文件中加入自定义信息
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <section name="Students" type="ConsoleApplication.StudentSectionHandler,ConsoleApplication,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null" />
- </configSections>
- <Students>
- <Student>
- <Name>Sonny.Lin</Name>
- <Age>30</Age>
- <Gender>Male</Gender>
- <Grade>G2</Grade>
- <Hobby>旅游</Hobby>
- </Student>
- <Student>
- <Name>Willim.Lin</Name>
- <Age>3</Age>
- <Gender>Male</Gender>
- <Hobby>玩、看电视</Hobby>
- </Student>
- </Students>
- </configuration>
注意:
1.section中定义了Students(xml)节点,而Students中定义了两个Student,所以这个处理程序应该返回List<Student>类型;
2.处理程序的type一定要用强类型,“完整类名 , 程序集名 , 版本信息 , 区域信息 , 公钥 ”,根据自己的不同名称需要更改;
4.测试程序入口
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- namespace ConsoleApplication {
- class Program {
- static void Main(string[] args) {
- List<Student> stuList = ConfigurationManager.GetSection("Students") as List<Student>;
- if (stuList != null) {
- foreach (Student stu in stuList) {
- Console.WriteLine(stu);
- }
- }
- }
- }
- }
下载地址:http://u.163.com/VmMfE
提取码:jiqul3zh