C#读取自定义的config
今天说下C#读写自定义config文件的各种方法。由于这类文章已经很多,但是大多数人举例子都是默认的在app.confg或者web.config进行读写,而不是一般的XML文件,我主要写的是一般的Xml文件,不是默认路径下的app.config.
通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件。今天我主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting.
首先来看下配置节点。
<?xml version="1.0" ?>
<configuration>
<configSections>
<section name="MySection1" type="ConfigApplicationDemo.MySection1, ConfigApplication" />
<section name="MySection2" type="ConfigApplicationDemo.MySection2, ConfigApplication" />
<section name="MySection3" type="ConfigApplicationDemo.MySection3, ConfigApplication" />
<section name="MySection4" type="ConfigApplicationDemo.MySection4, ConfigApplication" />
</configSections>
<MySection1 name="Halia" url="http://www.cnblogs.com/halia/">
</MySection1>
<MySection2>
<users username="halia" password="test2012"></users> </MySection2>
<MySection3>
<add key="aa" value="11111"></add>
<add key="bb" value="22222"></add>
<add key="cc" value="33333"></add>
</MySection3>
<MySection4>
<add name="aa" id="11111" role="test"></add>
<add name="bb" id="22222" role="key"></add>
<add name="cc" id="33333" role="rest"></add>
</MySection4>
</configuration>
这里大家可以看到我定义了四种不同的section,其中前两种介绍的人很多,这里不多赘述,先看看第三种。
<MySection3>
<add key="aa" value="11111"></add>
<add key="bb" value="22222"></add>
<add key="cc" value="33333"></add>
</MySection3>
这个配置具有一系列数据,这时候就要用到collection,代码如下:
public class MySection3 : ConfigurationSection // 所有配置节点都要选择这个基类
{
private static readonly ConfigurationProperty s_property = new ConfigurationProperty(string.Empty, typeof(TheKeyValueCollection), null,
ConfigurationPropertyOptions.IsDefaultCollection); [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public TheKeyValueCollection KeyValues
{
get
{
return (TheKeyValueCollection)base[s_property];
}
} [ConfigurationCollection(typeof(TheKeyValue))]
public class TheKeyValueCollection: ConfigurationElementCollection // 自定义一个集合
{
new public TheKeyValuethis[string name]
{ get
{
return (TheKeyValue)base.BaseGet(name);
}
}
// 下面二个方法中抽象类中必须要实现的。
protected override ConfigurationElement CreateNewElement()
{
return new TheKeyValue();
}
protected override object GetElementKey
(
ConfigurationElement element)
{
return ((TheKeyValue)element).Key;
}
} public class TheKeyValue : ConfigurationElement // 集合中的每个元素
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return this["value"].ToString(); }
set { this["value"] = value; } }
}
}
上面的三个class做了三件事:
1. 为每个集合中的参数项创建一个从ConfigurationElement继承的派生类。
2. 为集合创建一个从ConfigurationElementCollection继承的集合类,具体在实现时主要就是调用基类的方法。
3. 在创建ConfigurationSection的继承类时,创建一个表示集合的属性就可以了,注意[ConfigurationProperty]的各参数。
然后就是读取config中的值,在读取自定节点时,我们需要调用ConfigurationManager.GetSection()得到配置节点,并转换成我们定义的配置节点类,然后就可以按照强类型的方式来访问了。
if (!string.IsNullOrEmpty(ConfigFile))
//这里的ConfigFile是你要读取的Xml文件的路径,如果为空,则使用默认的app.config文件
{ var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = ConfigFile };
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
MySection3 configSection = (MySection3 )config.GetSection("MySection3");
}
else
{
//Get the default config app.config
MySection3 configSection = (MySection3 )ConfigurationManager.GetSection("MySection3");
} var values = from kv in configSection.KeyValues.Cast<TheKeyValue>()
select new
{ key=kv.Key, val=kv.Value)};
我们在来看下section4的配置:
<MySection4>
<add name="aa" id="11111" role="test"></add>
<add name="bb" id="22222" role="key"></add>
<add name="cc" id="33333" role="rest"></add>
</MySection4>
这个关于Collection的写法和第三个差不多,不同之处在于属性的定义是不同的。
public class TheKeyValue : ConfigurationElement // 集合中的每个元素
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return this["name"].ToString(); }
set { this["name"] = value; }
} [ConfigurationProperty("id", IsRequired = true)]
public string Id
{
get { return this["id"].ToString(); }
set { this["id"] = value; } }
} [ConfigurationProperty("role", IsRequired = true)]
public string Role
{
get { return this["role"].ToString(); }
set { this["role"] = value; } }
}
}
然后是获取相应的值:
if (!string.IsNullOrEmpty(ConfigFile))
//这里的ConfigFile是你要读取的Xml文件的路径,如果为空,则使用默认的app.config文件
{ var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = ConfigFile };
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
MySection4 configSection = (MySection4 )config.GetSection("MySection4");
}
else
{
//Get the default config app.config
MySection4 configSection = (MySection4 )ConfigurationManager.GetSection("MySection4");
} var values = from v in configSection.KeyValues.Cast<TheKeyValue>()
select new
{ name=v.Name, id=v.Id,role=v.Role)};
上面就是关于自定义section的一些分享,这里还要说一下section里面的type
<section name="MySection1" type="ConfigApplicationDemo.MySection1, ConfigApplication" />
关于这个type的定义,逗号前面ConfigApplicationDemo.MySection1, 需要对应你的namespace和你的section类的名字,逗号后面需要对应的是你编译出来的dll的名字,很多情况下namespace和dll名字是一样的,但是出现不一样的情况一定要注意,不然type定义不好,或版本不对,会报错,错误如下,程序会告诉你找不到指定的file或者section。
An error occurred creating the configuration section handler for XXX: Could not load type..
C#读取自定义的config的更多相关文章
- springboot 学习之路 22 (读取自定义文件)
springboot读取自定义的properties文件: package com.huhy.demo.properties; import lombok.Data; import org.sprin ...
- Springboot读取自定义配置文件的几种方法
一.读取核心配置文件 核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单. ...
- Springboot(二)-application.yml默认的配置项以及读取自定义配置
写在前面 ===== spring-boot 版本:2.0.0.RELEASE ===== 读取自定义配置 1.配置文件:sys.properties supply.place=云南 supply.c ...
- [C#常用代码]类库中读取解决方案web.Config字符串
对于类库里读取解决方案web.config文件里字符串的方法一.读取键值对的方法:1.添加引用using System.Configuration;2.web.Config配置节<appSett ...
- Android读取自定义View属性
Android读取自定义View属性 attrs.xml : <?xml version="1.0" encoding="utf-8"?> < ...
- C# 如何获取自定义的config中节点的值,并修改节点的值
现定义一个方法 DIYConfigHelper.cs using System; using System.Xml; using System.Configuration; using System. ...
- Springboot中读取自定义名称properties的
Springboot读取自定义的配置文件时候,使用@value,一定要指定配置文件的位置! 否则报错参数化异常!
- Spring Boot读取自定义外部属性
测试的环境:Spring Boot2 + Maven +lombok 准备需要用到的基础类: public class People { private String name; private St ...
- .net 中读取自定义Config文件
今天做一个windows插件式服务程序,插件有时要读取配置文件的设置,但是服务是动态加载到服务上的,没有办法作到动态修改服务的配置文件(app.config).在.net 2.0中有一个Configu ...
随机推荐
- ACM程序设计选修课——Problem E:(ds:图)公路村村通(Prim)
问题 E: (ds:图)公路村村通 时间限制: 1 Sec 内存限制: 128 MB 提交: 9 解决: 5 题目描述 现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本, ...
- [USACO07NOV]牛继电器Cow Relays (最短路,DP)
题目链接 Solution 非正解 似乎比较蛇啊,先个一个部分分做法,最短路+\(DP\). 在求最短路的堆或者队列中存储元素 \(dis_{i,j}\) 代表 \(i\) 这个节点,走了 \(j\) ...
- Java面试题之继承、组合、聚合有什么区别
继承:他是is-a的关系,指一个类继承另外一个类的功能 例如:public class A extends B { } 聚合:他是has-a 例如:public class A{ List<B& ...
- 自己关于Django的一些实践
一 render() redirect() HttpResponse() 响应 是个什么东西 def login(request): if request.method=='POST': userna ...
- spring和resteasy 的集成方式
spring和resteasy集成,三种主要的方式, 对于和jboss as7的集成不需要做任何工作,jboss默认集成了resteasy,只需要对业务pojo做一些jax-rs的注解标注即可.这里讲 ...
- 【CF387D】George and Interesting Graph(二分图最大匹配)
题意:给定一张n点m边没有重边的有向图,定义一个有趣图为:存在一个中心点满足以下性质: 1.除了这个中心点之外其他的点都要满足存在两个出度和两个入度. 2.中心 u 需要对任意顶点 v(包括自己)有一 ...
- 使用redis-stat来监控redis实例
https://blog.csdn.net/xiao_jun_0820/article/details/78189576 https://blog.csdn.net/u010022051/articl ...
- js-input file 文件上传(照片,视频,音频)
在此做一个笔记 <input type="file" accept="image/*" capture="camera"> &l ...
- UVA 10635 Prince and Princess【LCS 问题转换为 LIS】
题目链接: http://acm.hust.edu.cn/vjudge/problem/visitOriginUrl.action?id=19051 题意: 有两个长度分别为p+1和q+1的由1到n2 ...
- Go -- 接口赋值
在go语言中,接口赋值分为2中情况: 1.将对象实例赋值给接口: 2.将一个接口赋值给另一个接口. 1.将对象实例赋值给接口: 要求对象实现了接口的所有方法. 2.将接口赋值给另一个接口: 假设接口A ...