文件的目录(若要对config配置文件进行操作,需要添加对的引用)
调用方式
//获取配置节数据
var obj= System.Configuration.ConfigurationManager.GetSection("myConfigSection");
1.App.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--自定义配置节声明 type="命名空间.类名,程序集名称"-->
<section name="myConfigSection" type="MyLibNameSpace.MyConfSection,MyLib"/>
</configSections>
<!--自定义配置节主体-->
<myConfigSection attrNo="1000" attrName="apple" attrInfo="hello section!">
<myChild childNo="1001" childName="lili"></myChild>
</myConfigSection>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
2.MyConfSection.cs
namespace MyLibNameSpace
{
public class MyConfSection : ConfigurationSection //必须继承 ConfigurationSection
{
[ConfigurationProperty("attrNo")] //声明属性名称,必须写,否则编译不报错但是执行报错,这个代码应该是执行的时候发挥作用
public virtual string attrNo
{
get
{
return (string)this["attrNo"];//此得益于父类的索引器
}
set
{
this["attrNo"] = value;
}
}
[ConfigurationProperty("attrName")]
public virtual string attrName
{
get
{
return (string)this["attrName"];//此得益于父类的索引器
}
set
{
this["attrName"] = value;
}
}
[ConfigurationProperty("attrInfo")]
public virtual string attrInfo
{
get
{
return (string)this["attrInfo"];//此得益于父类的索引器
}
set
{
this["attrInfo"] = value;
}
}
[ConfigurationProperty("myChild")]
public virtual MyConfChild MyChild
{
get
{
return (MyConfChild)this["myChild"];//此得益于父类的索引器
}
set
{
this["myChild"] = value;
}
}
}
}
3.MyConfChild.cs
namespace MyLibNameSpace
{
public class MyConfChild : ConfigurationElement
{
[ConfigurationProperty("childNo")]
public virtual string childNo
{
get {
return (string)this["childNo"];//此得益于父类的索引器
}
set {
this["childNo"] = value;
}
}
[ConfigurationProperty("childName")]
public virtual string childName
{
get
{
return (string)this["childName"];//此得益于父类的索引器
}
set
{
this["childName"] = value;
}
}
}
}
PS:有的配置节点为什么没有在<configSections></configSections> 里面声明就可以直接使用?
回答:
在C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config里有一个machine.config文件, 里面包含常用的appSettings 等节点的声明,所以不是不用声明,是默认已经声明好了。