在.net中读写config文件的各种方法

今天谈谈在.net中读写config文件的各种方法。 在这篇博客中,我将介绍各种配置文件的读写操作。 由于内容较为直观,因此没有过多的空道理,只有实实在在的演示代码, 目的只为了再现实战开发中的各种场景。希望大家能喜欢。

通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件。 今天的博客示例也将介绍这二大类的配置文件的各类操作。 在config文件中,我将主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting 。

请明:本文所说的config文件特指app.config或者web.config,而不是一般的XML文件。 在这类配置文件中,由于.net framework已经为它们定义了一些配置节点,因此我们并不能简单地通过序列化的方式去读写它。

回到顶部

config文件 - 自定义配置节点

为什么要自定义的配置节点?

确实,有很多人在使用config文件都是直接使用appSetting的,把所有的配置参数全都塞到那里,这样做虽然不错, 但是如果参数过多,这种做法的缺点也会明显地暴露出来:appSetting中的配置参数项只能按key名来访问,不能支持复杂的层次节点也不支持强类型, 而且由于全都只使用这一个集合,你会发现:完全不相干的参数也要放在一起!

想摆脱这种困扰吗?自定义的配置节点将是解决这个问题的一种可行方法。

首先,我们来看一下如何在app.config或者web.config中增加一个自定义的配置节点。 在这篇博客中,我将介绍4种自定义配置节点的方式,最终的配置文件如下:

复制代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" />
        <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" />
        <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" />
        <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" />
    </configSections>

    <MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111>

    <MySection222>
        <users username="fish" password="liqifeng"></users>
    </MySection222>

    <MySection444>
        <add key="aa" value="11111"></add>
        <add key="bb" value="22222"></add>
        <add key="cc" value="33333"></add>
    </MySection444>

    <MySection333>
        <Command1>
            <![CDATA[
                create procedure ChangeProductQuantity(
                    @ProductID int,
                    @Quantity int
                )
                as
                update Products set Quantity = @Quantity 
                where ProductID = @ProductID;
            ]]>
        </Command1>
        <Command2>
            <![CDATA[
                create procedure DeleteCategory(
                    @CategoryID int
                )
                as
                delete from Categories
                where CategoryID = @CategoryID;
            ]]>
        </Command2>
    </MySection333>    
</configuration>

同时,我还提供所有的示例代码(文章结尾处可供下载),演示程序的界面如下:

回到顶部

config文件 - Property

先来看最简单的自定义节点,每个配置值以属性方式存在:

复制代码
<MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111>

实现代码如下:

复制代码
public class MySection1 : ConfigurationSection
{
    [ConfigurationProperty("username", IsRequired = true)]
    public string UserName
    {
        get { return this["username"].ToString(); }
        set { this["username"] = value; }
    }

    [ConfigurationProperty("url", IsRequired = true)]
    public string Url
    {
        get { return this["url"].ToString(); }
        set { this["url"] = value; }
    }
}

小结:

  1. 自定义一个类,以ConfigurationSection为基类,各个属性要加上ConfigurationProperty ,ConfigurationProperty的构造函数中传入的name字符串将会用于config文件中,表示各参数的属性名称。

  2. 属性的值的读写要调用this\[\],由基类去保存,请不要自行设计Field来保存。

  3. 为了能使用配置节点能被解析,需要在<configSections>中注册: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要与<MySection111 ..... >是对应的。

说明:下面将要介绍另三种配置节点,虽然复杂一点,但是一些基础的东西与这个节点是一样的,所以后面我就不再重复说明了。

回到顶部

config文件 - Element

再来看个复杂点的,每个配置项以XML元素的方式存在:

复制代码
<MySection222>
    <users username="fish" password="liqifeng"></users>
</MySection222>

实现代码如下:

小结:

  1. 自定义一个类,以ConfigurationSection为基类,各个属性除了要加上ConfigurationProperty

  2. 类型也是自定义的,具体的配置属性写在ConfigurationElement的继承类中。

回到顶部

config文件 - CDATA

有时配置参数包含较长的文本,比如:一段SQL脚本,或者一段HTML代码,那么,就需要CDATA节点了。假设要实现一个配置,包含二段SQL脚本:

复制代码
<MySection333>
    <Command1>
        <![CDATA[
            create procedure ChangeProductQuantity(
                @ProductID int,
                @Quantity int
            )
            as
            update Products set Quantity = @Quantity 
            where ProductID = @ProductID;
        ]]>
    </Command1>
    <Command2>
        <![CDATA[
            create procedure DeleteCategory(
                @CategoryID int
            )
            as
            delete from Categories
            where CategoryID = @CategoryID;
        ]]>
    </Command2>
</MySection333>

实现代码如下:

小结:

  1. 在实现上大体可参考MySection2,

  2. 每个ConfigurationElement由我们来控制如何读写XML,也就是要重载方法SerializeElement,DeserializeElement

回到顶部

config文件 - Collection

复制代码
<MySection444>
    <add key="aa" value="11111"></add>
    <add key="bb" value="22222"></add>
    <add key="cc" value="33333"></add>
</MySection444>

这种类似的配置方式,在ASP.NET的HttpHandler, HttpModule中太常见了,想不想知道如何实现它们? 代码如下:

小结:

  1. 为每个集合中的参数项创建一个从ConfigurationElement继承的派生类,可参考MySection1

  2. 为集合创建一个从ConfigurationElementCollection继承的集合类,具体在实现时主要就是调用基类的方法。

  3. 在创建ConfigurationSection的继承类时,创建一个表示集合的属性就可以了,注意ConfigurationProperty的各参数。

回到顶部

config文件 - 读与写

前面我逐个介绍了4种自定义的配置节点的实现类,下面再来看一下如何读写它们。

读取配置参数:

复制代码
MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111");
txtUsername1.Text = mySectioin1.UserName;
txtUrl1.Text = mySectioin1.Url;


MySection2 mySectioin2 = (MySection2)ConfigurationManager.GetSection("MySection222");
txtUsername2.Text = mySectioin2.Users.UserName;
txtUrl2.Text = mySectioin2.Users.Password;


MySection3 mySection3 = (MySection3)ConfigurationManager.GetSection("MySection333");
txtCommand1.Text = mySection3.Command1.CommandText.Trim();
txtCommand2.Text = mySection3.Command2.CommandText.Trim();


MySection4 mySection4 = (MySection4)ConfigurationManager.GetSection("MySection444");
txtKeyValues.Text = string.Join("\r\n",
                        (from kv in mySection4.KeyValues.Cast<MyKeyValueSetting>()
                         let s = string.Format("{0}={1}", kv.Key, kv.Value)
                         select s).ToArray());

小结:在读取自定节点时,我们需要调用ConfigurationManager.GetSection()得到配置节点,并转换成我们定义的配置节点类,然后就可以按照强类型的方式来访问了。

写配置文件:

复制代码
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

MySection1 mySectioin1 = config.GetSection("MySection111") as MySection1;
mySectioin1.UserName = txtUsername1.Text.Trim();
mySectioin1.Url = txtUrl1.Text.Trim();
相关推荐
tachibana21 小时前
hot100 回文链表(234)
java·网络·数据结构·leetcode·链表
可乐ea1 小时前
【Java八股|第10篇】Java 中的包装类和自动拆装箱
java·面试题·包装类·java八股
zfoo-framework2 小时前
mongo最佳实战(from mongo中文社区)
java
深盾科技_Virbox2 小时前
加密狗授权能力选型:从授权模型到全生命周期管理
java·网络·数据库
峥无2 小时前
深入理解MySQL事务与MVCC机制
数据库·mysql
行思理3 小时前
MongoDB 大数据备份,新手教程
数据库·mongodb
. . . . .3 小时前
Egg框架深入
java·开发语言
RainCity3 小时前
Java Swing 自定义组件库分享(十三)
java·笔记·后端
城数派4 小时前
1950-2026年中国0.1°逐月平均气温栅格数据集
数据库·信息可视化