今天说下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的更多相关文章

  1. springboot 学习之路 22 (读取自定义文件)

    springboot读取自定义的properties文件: package com.huhy.demo.properties; import lombok.Data; import org.sprin ...

  2. Springboot读取自定义配置文件的几种方法

    一.读取核心配置文件 核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单. ...

  3. Springboot(二)-application.yml默认的配置项以及读取自定义配置

    写在前面 ===== spring-boot 版本:2.0.0.RELEASE ===== 读取自定义配置 1.配置文件:sys.properties supply.place=云南 supply.c ...

  4. [C#常用代码]类库中读取解决方案web.Config字符串

    对于类库里读取解决方案web.config文件里字符串的方法一.读取键值对的方法:1.添加引用using System.Configuration;2.web.Config配置节<appSett ...

  5. Android读取自定义View属性

    Android读取自定义View属性 attrs.xml : <?xml version="1.0" encoding="utf-8"?> < ...

  6. C# 如何获取自定义的config中节点的值,并修改节点的值

    现定义一个方法 DIYConfigHelper.cs using System; using System.Xml; using System.Configuration; using System. ...

  7. Springboot中读取自定义名称properties的

    Springboot读取自定义的配置文件时候,使用@value,一定要指定配置文件的位置!  否则报错参数化异常!

  8. Spring Boot读取自定义外部属性

    测试的环境:Spring Boot2 + Maven +lombok 准备需要用到的基础类: public class People { private String name; private St ...

  9. .net 中读取自定义Config文件

    今天做一个windows插件式服务程序,插件有时要读取配置文件的设置,但是服务是动态加载到服务上的,没有办法作到动态修改服务的配置文件(app.config).在.net 2.0中有一个Configu ...

随机推荐

  1. 刷题总结——天使玩偶(bzoj2716)

    题目: Description Input Output HINT 题解: 学了cdq后近期最后一道题···然而tm还是搞了1个半小时才tm搞出来······ 先说思路:对于绝对值,我们采取类似于旋转 ...

  2. P2730 魔板 Magic Squares (搜索)

    题目链接 Solution 这道题,我是用 \(map\) 做的. 具体实现,我们用一个 \(string\) 类型表示任意一种情况. 可以知道,排列最多只有 \(8!\) 个. 然后就是直接的广搜了 ...

  3. [CQOI2010] 扑克牌 (二分答案,巧解)

    Description 你有n种牌,第i种牌的数目为ci.另外有一种特殊的牌:joker,它的数目是m.你可以用每种牌各一张来组成一套牌,也可以用一张joker和除了某一种牌以外的其他牌各一张组成1套 ...

  4. C#中DataTable中Rows.Add 和 ImportRow 对比

    最近参加项目中,数据操作基本都是用DataTable的操作,老代码中有些地方用到DataTable.Rows.Add又有些代码用的DataTable.ImportRow,于是就对比了一下 VS查询说明 ...

  5. Codeforces 842C Ilya And The Tree 树上gcd

    题目链接 题意 给定一棵根为\(1\)的树.定义每个点的美丽值为根节点到它的路径上所有点的\(gcd\)值.但是对于每个点,在计算它的美丽值时,可以将这条路径上某个点的值变为\(0\)来最大化它的美丽 ...

  6. 在tomcat发布项目遇到的问题

    今天从SVN上把系统导入本地发生了异常,问题如下: java.math.BigInteger cannot be cast to java.lang.Long 百度一番后发现是因为使用Mysql8.0 ...

  7. html5(拖拽1)

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  8. Android中沉浸式状态栏的应用

    在Android5.0版本后,谷歌公司为Android系统加入了很多新特性,刷新了Android用户的体验度.而其中的一个新特性就是沉浸式状态栏.那么问题来了,很多非移动端的小伙伴就要问了,什么是沉浸 ...

  9. Hibernate游记——装备篇《一》(基础配置详解)

    Hibernate配置文件可以有两种格式,一种是 hibernate.properties ,另一种是 hibernate.cfg.xml 后者稍微方便一些,当增加hbm映射文件的时候,可以直接在 h ...

  10. Codechef Eugene and big number(矩阵快速幂)

    题目链接 Eugene and big number 题目转化为 $f(n) = m * f(n - 1) + a$ $f(n + 1) = m * f(n) + a$ 两式相减得 $f(n + 1) ...