读写config,xml配置文件
尊重原创:http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html#_labelStart 今天谈谈在.net中读写config文件的各种方法。在这篇博客中,我将介绍各种配置文件的读写操作。由于内容较为直观,因此没有过多的空道理,只有实实在在的演示代码,目的只为了再现实战开发中的各种场景。希望大家能喜欢。 通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件。今天的博客示例也将介绍这二大类的配置文件的各类操作。在config文件中,我将主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting 。 请明:本文所说的config文件特指app.config或者web.config,而不是一般的XML文件。在这类配置文件中,由于.net framework已经为它们定义了一些配置节点,因此我们并不能简单地通过序列化的方式去读写它。 config文件 - 自定义配置节点 为什么要自定义的配置节点? 想摆脱这种困扰吗?自定义的配置节点将是解决这个问题的一种可行方法。 首先,我们来看一下如何在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="22222"></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; } } } 小结: 说明:下面将要介绍另三种配置节点,虽然复杂一点,但是一些基础的东西与这个节点是一样的,所以后面我就不再重复说明了。 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; } } } 小结: 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; } } } 小结:
config文件 - Collection
<MySection444> <add key="aa" value="22222"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> 这种类似的配置方式,在ASP.NET的HttpHandler,HttpModule中太常见了,想不想知道如何实现它们? 代码如下: 小结:
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("rn",(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();即可。 注意: 读写 .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 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); } 小结: XmlHelper的实现如下: xml配置文件 - CDATA 在前面的演示中,有个不完美的地方,我将SQL脚本以普通字符串的形式输出到XML中了: <CommandText>insret into .....</CommandText> 显然,现实中的SQL脚本都是比较长的,而且还可能会包含一些特殊的字符,这种做法是不可取的,好的处理方式应该是将它以CDATA的形式保存,为了实现这个目标,我们就不能直接按照普通字符串的方式来处理了,这里我定义了一个类 MyCDATA: 我将使用这个类来控制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 = "rn"; settings.OmitXmlDeclaration = true; settings.IndentChars = "t"; XmlWriter writer = XmlWriter.Create(stream,settings); 使用上面这段代码,我可以: 前面介绍了读写XML的方法,可是,如何开始呢? 由于没有XML文件,程序也没法读取,那么如何得到一个格式正确的XML呢?答案是:先写代码,创建一个要读取的对象,随便输入一些垃圾数据,然后将它写入XML(反序列化),然后,我们可以参考生成的XML文件的具体格式,或者新增其它的节点(列表),或者修改前面所说的垃圾数据,最终得到可以使用的,有着正确格式的XML文件。 配置参数的建议保存方式 经常见到有很多组件或者框架,都喜欢把配置参数放在config文件中,那些设计者或许认为他们的作品的参数较复杂,还喜欢搞自定义的配置节点。结果就是:config文件中一大堆的配置参数。最麻烦的是:下次其它项目还要使用这个东西时,还得继续配置! .net一直提倡XCOPY,但我发现遵守这个约定的组件或者框架还真不多。所以,我想建议大家在设计组件或者框架的时候: config文件与XML文件的差别 从本质上说,config文件也是XML文件,但它们有一点差别,不仅仅是因为.net framework为config文件预定义了许多配置节。对于ASP.NET应用程序来说,如果我们将参数放在web.config中,那么,只要修改了web.config,网站也将会重新启动,此时有一个好处:我们的代码总是能以最新的参数运行。另一方面,也有一个坏处:或许由于种种原因,我们并不希望网站被重启,毕竟重启网站会花费一些时间,这会影响网站的响应。对于这个特性,我只能说,没有办法,web.config就是这样。 然而,当我们使用XML时,显然不能直接得到以上所说的特性。因为XML文件是由我们自己来维护的。 到这里,您有没有想过:我如何在使用XML时也能拥有那些优点呢? 我希望在用户修改了配置文件后,程序能立刻以最新的参数运行,而且不用重新网站。(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |