自定义config文件section操作
IConfigurationSectionHandler
给config文件添加自定义section
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ProjectSection" type="ConsoleApplication1.ProjectSection, ConsoleApplication1"/>
</configSections>
<ProjectSection name="ProjectCompany">
<role name="administartor"/>
<role name="manager"/>
<role name="support"/>
</ProjectSection>
</configuration>
1
using System;2
using System.Collections.Generic;3
using System.Configuration;4
using System.Xml;5

6
namespace ConsoleApplication17


{8
internal class Program9

{10
private static void Main()11

{12
ProjectSection projectSection = ConfigurationManager.GetSection("ProjectSection") as ProjectSection;13

14
Console.WriteLine(projectSection.name);15
foreach (var role in projectSection.roles)16

{17
Console.WriteLine(role.name);18
}19

20
Console.ReadLine();21
}22
}23

24
public class Role25

{26

public string name
{ get; set; }27
}28

29
public class ProjectSection : IConfigurationSectionHandler30

{31

public Role[] roles
{ get; set; }32

33

public string name
{ get; set; }34

35
public object Create(object parent, object configContext, XmlNode section)36

{37
ProjectSection ps = new ProjectSection();38
ps.name = section.Attributes["name"].Value;39
if (parent != null)40

{41
ps = (ProjectSection)parent;42
}43

44
List<Role> list = new List<Role>();45
foreach (XmlNode node in section.ChildNodes)46

{47
if (null != node.Attributes)48

{49
Role item = new Role();50
item.name = node.Attributes["name"].Value;51
list.Add(item);52
}53
}54
ps.roles = list.ToArray();55
return ps;56
}57
}58
}

浙公网安备 33010602011771号