有时候,我们需要在应用程序配置文件(app.config)或网站配置文件(web.config)中自定义一些信息,靠appSetting和connectionString不能满足需求。
首先在配置文件中添加configSections节,说明自定义配置节的名称,并制定读取方式(用什么处理程序来读取),这里我演示自定义处理程序读取,自定义处理程序必须实现IConfigurationSectionHandler接口
1.定义实体类Student
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Text;
- namespaceConsoleApplication{
- publicenumGender{
- Female,
- Male
- }
- publicenumGrade{
- G1,
- G2,
- G3
- }
- publicclassStudent{
- publicstringName{get;set;}
- publicintAge{get;set;}
- publicGenderGender{get;set;}
- publicGradeGrade{get;set;}
- publicstringHobby{get;set;}
- publicoverridestringToString(){
- returnstring.Format("我是{0}{1},今年{2}岁,我喜欢{3}。",
- Name,
- Gender==Gender.Male?"男生":"女生",
- Age,
- Hobby);
- }
- }
- }
2.定义自定义处理程序StudentSectionHandler来创建对象
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Text;
- usingSystem.Configuration;
- usingSystem.Xml;
- namespaceConsoleApplication{
- publicclassStudentSectionHandler:IConfigurationSectionHandler{
- publicobjectCreate(objectparent,objectconfigContext,XmlNodesection){
- List<Student>stuList=newList<Student>();
- try{
- foreach(XmlNodestuNodeinsection.ChildNodes){
- Studentstu=newStudent();
- foreach(XmlNodenodeinstuNode.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(Exceptionex){
- throwex;
- }
- returnstuList;
- }
- }
- }
3.配置文件中加入自定义信息
- <?xmlversion="1.0"encoding="utf-8"?>
- <configuration>
- <configSections>
- <sectionname="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.测试程序入口
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Text;
- usingSystem.Configuration;
- namespaceConsoleApplication{
- classProgram{
- staticvoidMain(string[]args){
- List<Student>stuList=ConfigurationManager.GetSection("Students")asList<Student>;
- if(stuList!=null){
- foreach(StudentstuinstuList){
- Console.WriteLine(stu);
- }
- }
- }
- }
- }
下载地址:http://u.163.com/VmMfE
提取码:jiqul3zh