C# WinForm开发中使用XML配置文件实例
本文介绍在使用C#开发WinForm程序时,如何使用自定义的XML配置文件。虽然也可以使用app.config,但命名方面很别扭。
我们在使用C#开发软件程序时,经常需要使用配置文件。虽然说VisualStudio里面也自带了app.config这个种配置文件,但用过的朋友都知道,在编译之后,这个app.config的名称会变成app.程序文件名.config,这多别扭啊!我们还是来自己定义一个配置文件吧。
配置文件就是用来保存一些数据的,那用xml再合适不过。那本文就介绍如何使用XML来作为C#程序的配置文件。
1、创建一个XML配置文件
比如我们要在配置文件设置一个数据库连接字符串,和一组SMTP发邮件的配置信息,那XML配置文件如下:
<?xmlversion="1.0"encoding="utf-8"?> <root> <connstring>provider=sqloledb;DataSource=127.0.0.1;InitialCatalog=splaybow;UserId=splaybow;Password=splaybow;</connstring> <!--EmailSMTPinfo--> <smtpip>127.0.0.1</smtpip> <smtpuser>splaybow@jb51.net</smtpuser> <smtppass>splaybow</smtppass> </root>
熟悉XML的朋友一看就知道是什么意思,也不需要小编多做解释了。
2、设置参数变量来接收配置文件中的值
创建一个配置类,这个类有很多属性,这些属性对应XML配置文件中的配置项。
假如这个类叫CConfig,那么CConfig.cs中设置如下一组变量:
//数据库配置信息 publicstaticstringConnString=""; //SMTP发信账号信息 publicstaticstringSmtpIp=""; publicstaticstringSmtpUser=""; publicstaticstringSmtpPass="";
3、读取配置文件中的值
///<summary> ///一次性读取配置文件 ///</summary> publicstaticvoidLoadConfig() { try { XmlDocumentxml=newXmlDocument(); stringxmlfile=GetXMLPath(); if(!File.Exists(xmlfile)) { thrownewException("配置文件不存在,路径:"+xmlfile); } xml.Load(xmlfile); stringtmpValue=null; //数据库连接字符串 if(xml.GetElementsByTagName("connstring").Count>0) { tmpValue=xml.DocumentElement["connstring"].InnerText.Trim(); CConfig.ConnString=tmpValue; } //smtp if(xml.GetElementsByTagName("smtpip").Count>0) { tmpValue=xml.DocumentElement["smtpip"].InnerText.Trim(); CConfig.SmtpIp=tmpValue; } if(xml.GetElementsByTagName("smtpuser").Count>0) { tmpValue=xml.DocumentElement["smtpuser"].InnerText.Trim(); CConfig.SmtpUser=tmpValue; } if(xml.GetElementsByTagName("smtppass").Count>0) { tmpValue=xml.DocumentElement["smtppass"].InnerText.Trim(); CConfig.SmtpPass=tmpValue; } } catch(Exceptionex) { CConfig.SaveLog("CConfig.LoadConfig()fail,error:"+ex.Message); Environment.Exit(-1); } }
4、配置项的使用
在程序开始时应该调用CConifg.LoadConfig()函数,将所有配置项的值载入到变量中。然后在需要用到配置值的时候,使用CConfig.ConnString即可。
关于C#开发WinForm时使用自定义的XML配置文件,本文就介绍这么多,希望对您有所帮助,谢谢!