当前位置: 移动技术网 > IT编程>开发语言>.net > 详解在.net中读写config文件的各种方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论
今天谈谈在.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="//www.jb51.net/"></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="//www.jb51.net/"></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>

实现代码如下:

public class mysection2 : configurationsection
{
  [configurationproperty("users", isrequired = true)]
  public mysectionelement users
  {
    get { return (mysectionelement)this["users"]; }
  }
}

public class mysectionelement : configurationelement
{
  [configurationproperty("username", isrequired = true)]
  public string username
  {
    get { return this["username"].tostring(); }
    set { this["username"] = value; }
  }

  [configurationproperty("password", isrequired = true)]
  public string password
  {
    get { return this["password"].tostring(); }
    set { this["password"] = value; }
  }
}

小结:

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>

实现代码如下:

public class mysection3 : configurationsection
{
  [configurationproperty("command1", isrequired = true)]
  public mytextelement command1
  {
    get { return (mytextelement)this["command1"]; }
  }

  [configurationproperty("command2", isrequired = true)]
  public mytextelement command2
  {
    get { return (mytextelement)this["command2"]; }
  }
}

public class mytextelement : configurationelement
{
  protected override void deserializeelement(system.xml.xmlreader reader, bool serializecollectionkey)
  {
    commandtext = reader.readelementcontentas(typeof(string), null) as string;
  }
  protected override bool serializeelement(system.xml.xmlwriter writer, bool serializecollectionkey)
  {
    if( writer != null )
      writer.writecdata(commandtext);
    return true;
  }

  [configurationproperty("data", isrequired = false)]
  public string commandtext
  {
    get { return this["data"].tostring(); }
    set { this["data"] = value; }
  }
}

小结:

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();

mysection2 mysection2 = config.getsection("mysection222") as mysection2;
mysection2.users.username = txtusername2.text.trim();
mysection2.users.password = txturl2.text.trim();

mysection3 mysection3 = config.getsection("mysection333") as mysection3;
mysection3.command1.commandtext = txtcommand1.text.trim();
mysection3.command2.commandtext = txtcommand2.text.trim();

mysection4 mysection4 = config.getsection("mysection444") as mysection4;
mysection4.keyvalues.clear();

(from s in txtkeyvalues.lines
   let p = s.indexof('=')
   where p > 0
   select new mykeyvaluesetting { key = s.substring(0, p), value = s.substring(p + 1) }
).tolist()
.foreach(kv => mysection4.keyvalues.add(kv));

config.save();

小结:在修改配置节点前,我们需要调用configurationmanager.openexeconfiguration(),然后调用config.getsection()在得到节点后,转成我们定义的节点类型, 然后就可以按照强类型的方式来修改我们定义的各参数项,最后调用config.save();即可。

注意:

1. .net为了优化配置节点的读取操作,会将数据缓存起来,如果希望使用修改后的结果生效,您还需要调用configurationmanager.refreshsection(".....")

2. 如果是修改web.config,则需要使用 webconfigurationmanager

读写 .net framework中已经定义的节点

前面一直在演示自定义的节点,那么如何读取.net framework中已经定义的节点呢?

假如我想读取下面配置节点中的发件人。

<system.net>
  <mailsettings>
    <smtp from="fish.q.li@newegg.com">
      <network />
    </smtp>
  </mailsettings>
</system.net>

读取配置参数:

smtpsection section = configurationmanager.getsection("system.net/mailsettings/smtp") as smtpsection;
labmailfrom.text = "mail from: " + section.from;

写配置文件:

configuration config = configurationmanager.openexeconfiguration(configurationuserlevel.none);

smtpsection section = config.getsection("system.net/mailsettings/smtp") as smtpsection;
section.from = "fish.q.li@newegg.com2";

config.save();

xml配置文件

前面演示在config文件中创建自定义配置节点的方法,那些方法也只适合在app.config或者web.config中,如果您的配置参数较多, 或者打算将一些数据以配置文件的形式单独保存,那么,直接读写整个xml将会更方便。 比如:我有一个实体类,我想将它保存在xml文件中,有可能是多条记录,也可能是一条。

这次我来反过来说,假如我们先定义了xml的结构,是下面这个样子的,那么我将怎么做呢?

<?xml version="1.0" encoding="utf-8"?>
<arrayofmycommand xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
         xmlns:xsd="http://www.w3.org/2001/xmlschema">
 <mycommand name="insretcustomer" database="mytestdb">
  <parameters>
   <parameter name="name" type="dbtype.string" />
   <parameter name="address" type="dbtype.string" />
  </parameters>
  <commandtext>insret into .....</commandtext>
 </mycommand>
</arrayofmycommand>

对于上面的这段xml结构,我们可以在c#中先定义下面的类,然后通过序列化及反序列化的方式来实现对它的读写。

c#类的定义如下:

public class mycommand
{
  [xmlattribute("name")]
  public string commandname;

  [xmlattribute]
  public string database;

  [xmlarrayitem("parameter")]
  public list<mycommandparameter> parameters = new list<mycommandparameter>();

  [xmlelement]
  public string commandtext;
}

public class mycommandparameter
{
  [xmlattribute("name")]
  public string paramname;

  [xmlattribute("type")]
  public string paramtype;
}

有了这二个c#类,读写这段xml就非常容易了。以下就是相应的读写代码:

private void btnreadxml_click(object sender, eventargs e)
{
  btnwritexml_click(null, null);
  
  list<mycommand> list = xmlhelper.xmldeserializefromfile<list<mycommand>>(xmlfilename, encoding.utf8);

  if( list.count > 0 )
    messagebox.show(list[0].commandname + ": " + list[0].commandtext,
      this.text, messageboxbuttons.ok, messageboxicon.information);

}

private void btnwritexml_click(object sender, eventargs e)
{
  mycommand command = new mycommand();
  command.commandname = "insretcustomer";
  command.database = "mytestdb";
  command.commandtext = "insret into .....";
  command.parameters.add(new mycommandparameter { paramname = "name", paramtype = "dbtype.string" });
  command.parameters.add(new mycommandparameter { paramname = "address", paramtype = "dbtype.string" });

  list<mycommand> list = new list<mycommand>(1);
  list.add(command);

  xmlhelper.xmlserializetofile(list, xmlfilename, encoding.utf8);
}

小结:

1. 读写整个xml最方便的方法是使用序列化反序列化。

2. 如果您希望某个参数以xml property的形式出现,那么需要使用[xmlattribute]修饰它。

3. 如果您希望某个参数以xml element的形式出现,那么需要使用[xmlelement]修饰它。

4. 如果您希望为某个list的项目指定elementname,则需要[xmlarrayitem]

5. 以上3个attribute都可以指定在xml中的映射别名。

6. 写xml的操作是通过xmlserializer.serialize()来实现的。

7. 读取xml文件是通过xmlserializer.deserialize来实现的。

8. list或array项,请不要使用[xmlelement],否则它们将以内联的形式提升到当前类,除非你再定义一个容器类。

xmlhelper的实现如下:

public static class xmlhelper
{
  private static void xmlserializeinternal(stream stream, object o, encoding encoding)
  {
    if( o == null )
      throw new argumentnullexception("o");
    if( encoding == null )
      throw new argumentnullexception("encoding");

    xmlserializer serializer = new xmlserializer(o.gettype());

    xmlwritersettings settings = new xmlwritersettings();
    settings.indent = true;
    settings.newlinechars = "\r\n";
    settings.encoding = encoding;
    settings.indentchars = "  ";

    using( xmlwriter writer = xmlwriter.create(stream, settings) ) {
      serializer.serialize(writer, o);
      writer.close();
    }
  }

  /// <summary>
  /// 将一个对象序列化为xml字符串
  /// </summary>
  /// <param name="o">要序列化的对象</param>
  /// <param name="encoding">编码方式</param>
  /// <returns>序列化产生的xml字符串</returns>
  public static string xmlserialize(object o, encoding encoding)
  {
    using( memorystream stream = new memorystream() ) {
      xmlserializeinternal(stream, o, encoding);

      stream.position = 0;
      using( streamreader reader = new streamreader(stream, encoding) ) {
        return reader.readtoend();
      }
    }
  }

  /// <summary>
  /// 将一个对象按xml序列化的方式写入到一个文件
  /// </summary>
  /// <param name="o">要序列化的对象</param>
  /// <param name="path">保存文件路径</param>
  /// <param name="encoding">编码方式</param>
  public static void xmlserializetofile(object o, string path, encoding encoding)
  {
    if( string.isnullorempty(path) )
      throw new argumentnullexception("path");

    using( filestream file = new filestream(path, filemode.create, fileaccess.write) ) {
      xmlserializeinternal(file, o, encoding);
    }
  }

  /// <summary>
  /// 从xml字符串中反序列化对象
  /// </summary>
  /// <typeparam name="t">结果对象类型</typeparam>
  /// <param name="s">包含对象的xml字符串</param>
  /// <param name="encoding">编码方式</param>
  /// <returns>反序列化得到的对象</returns>
  public static t xmldeserialize<t>(string s, encoding encoding)
  {
    if( string.isnullorempty(s) )
      throw new argumentnullexception("s");
    if( encoding == null )
      throw new argumentnullexception("encoding");

    xmlserializer myserializer = new xmlserializer(typeof(t));
    using( memorystream ms = new memorystream(encoding.getbytes(s)) ) {
      using( streamreader sr = new streamreader(ms, encoding) ) {
        return (t)myserializer.deserialize(sr);
      }
    }
  }

  /// <summary>
  /// 读入一个文件,并按xml的方式反序列化对象。
  /// </summary>
  /// <typeparam name="t">结果对象类型</typeparam>
  /// <param name="path">文件路径</param>
  /// <param name="encoding">编码方式</param>
  /// <returns>反序列化得到的对象</returns>
  public static t xmldeserializefromfile<t>(string path, encoding encoding)
  {
    if( string.isnullorempty(path) )
      throw new argumentnullexception("path");
    if( encoding == null )
      throw new argumentnullexception("encoding");

    string xml = file.readalltext(path, encoding);
    return xmldeserialize<t>(xml, encoding);
  }
}

xml配置文件 - cdata

在前面的演示中,有个不完美的地方,我将sql脚本以普通字符串的形式输出到xml中了:

<commandtext>insret into .....</commandtext>

显然,现实中的sql脚本都是比较长的,而且还可能会包含一些特殊的字符,这种做法是不可取的,好的处理方式应该是将它以cdata的形式保存, 为了实现这个目标,我们就不能直接按照普通字符串的方式来处理了,这里我定义了一个类 mycdata:

public class mycdata : ixmlserializable
{
  private string _value;

  public mycdata() { }

  public mycdata(string value)
  {
    this._value = value;
  }

  public string value
  {
    get { return _value; }
  }

  xmlschema ixmlserializable.getschema()
  {
    return null;
  }

  void ixmlserializable.readxml(xmlreader reader)
  {
    this._value = reader.readelementcontentasstring();
  }

  void ixmlserializable.writexml(xmlwriter writer)
  {
    writer.writecdata(this._value);
  }

  public override string tostring()
  {
    return this._value;
  }

  public static implicit operator mycdata(string text)
  {
    return new mycdata(text);
  }
}

我将使用这个类来控制commandtext在xml序列化及反序列化的行为,让它写成一个cdata形式, 因此,我还需要修改commandtext的定义,改成这个样子:

public mycdata commandtext;

最终,得到的结果是:

<?xml version="1.0" encoding="utf-8"?>
<arrayofmycommand xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
         xmlns:xsd="http://www.w3.org/2001/xmlschema">
 <mycommand name="insretcustomer" database="mytestdb">
  <parameters>
   <parameter name="name" type="dbtype.string" />
   <parameter name="address" type="dbtype.string" />
  </parameters>
  <commandtext><![cdata[insret into .....]]></commandtext>
 </mycommand>
</arrayofmycommand>

xml文件读写注意事项

通常,我们使用使用xmlserializer.serialize()得到的xml字符串的开头处,包含一段xml声明元素:

<?xml version="1.0" encoding="utf-8"?>

由于各种原因,有时候可能不需要它。为了让这行字符消失,我见过有使用正则表达式去删除它的,也有直接分析字符串去删除它的。 这些方法,要么浪费程序性能,要么就要多写些奇怪的代码。总之,就是看起来很别扭。 其实,我们可以反过来想一下:能不能在序列化时,不输出它呢? 不输出它,不就达到我们期望的目的了吗?

在xml序列化时,有个xmlwritersettings是用于控制写xml的一些行为的,它有一个omitxmldeclaration属性,就是专门用来控制要不要输出那行xml声明的。 而且,这个xmlwritersettings还有其它的一些常用属性。请看以下演示代码:

using( memorystream stream = new memorystream() ) {
  xmlwritersettings settings = new xmlwritersettings();
  settings.indent = true;
  settings.newlinechars = "\r\n";
  settings.omitxmldeclaration = true;
  settings.indentchars = "\t";

  xmlwriter writer = xmlwriter.create(stream, settings);

使用上面这段代码,我可以:

1. 不输出xml声明。

2. 指定换行符。

3. 指定缩进字符。

如果不使用这个类,恐怕还真的不能控制xmlserializer.serialize()的行为。

前面介绍了读写xml的方法,可是,如何开始呢? 由于没有xml文件,程序也没法读取,那么如何得到一个格式正确的xml呢? 答案是:先写代码,创建一个要读取的对象,随便输入一些垃圾数据,然后将它写入xml(反序列化), 然后,我们可以参考生成的xml文件的具体格式,或者新增其它的节点(列表), 或者修改前面所说的垃圾数据,最终得到可以使用的,有着正确格式的xml文件。

配置参数的建议保存方式

经常见到有很多组件或者框架,都喜欢把配置参数放在config文件中, 那些设计者或许认为他们的作品的参数较复杂,还喜欢搞自定义的配置节点。 结果就是:config文件中一大堆的配置参数。最麻烦的是:下次其它项目还要使用这个东西时,还得继续配置!

.net一直提倡xcopy,但我发现遵守这个约定的组件或者框架还真不多。 所以,我想建议大家在设计组件或者框架的时候:

1. 请不要把你们的参数放在config文件中,那种配置真的不方便【复用】。

2. 能不能同时提供配置文件以及api接口的方式公开参数,由用户来决定如何选择配置参数的保存方式。

config文件与xml文件的差别

从本质上说,config文件也是xml文件,但它们有一点差别,不仅仅是因为.net framework为config文件预定义了许多配置节。 对于asp.net应用程序来说,如果我们将参数放在web.config中,那么,只要修改了web.config,网站也将会重新启动, 此时有一个好处:我们的代码总是能以最新的参数运行。另一方面,也有一个坏处:或许由于种种原因,我们并不希望网站被重启, 毕竟重启网站会花费一些时间,这会影响网站的响应。 对于这个特性,我只能说,没有办法,web.config就是这样。

然而,当我们使用xml时,显然不能直接得到以上所说的特性。因为xml文件是由我们自己来维护的。

到这里,您有没有想过:我如何在使用xml时也能拥有那些优点呢?

我希望在用户修改了配置文件后,程序能立刻以最新的参数运行,而且不用重新网站。

本文的所有示例代码可以点击此处下载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网