我们在使用C#开发软件程序时,经常需要使用配置文件。虽然说Visual Studio里面也自带了app.config这个种配置文件,但用过的朋友都知道,在编译之后,这个app.config的名称会变成app.程序文件名.config,这多别扭啊!我们还是来自己定义一个配置文件吧。
配置文件就是用来保存一些数据的,那用xml再合适不过。那本文就介绍如何使用XML来作为C#程序的配置文件。
1、创建一个XML配置文件
比如我们要在配置文件设置一个数据库连接字符串,和一组SMTP发邮件的配置信息,那XML配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<connstring>provider=sqloledb;Data Source=127.0.0.1;Initial Catalog=splaybow;User Id=splaybow;Password=splaybow;</connstring>
<!--Email SMTP info-->
<smtpip>127.0.0.1</smtpip>
<smtpuser>splaybow@splaybow.com</smtpuser>
<smtppass>splaybow</smtppass>
</root>
熟悉XML的朋友一看就知道是什么意思,也不需要洪哥多做解释了。
2、设置参数变量来接收配置文件中的值
创建一个配置类,这个类有很多属性,这些属性对应XML配置文件中的配置项。
假如这个类叫CConfig,那么CConfig.cs中设置如下一组变量:
//数据库配置信息
public static string ConnString = "";
//SMTP发信账号信息
public static string SmtpIp = "";
public static string SmtpUser = "";
public static string SmtpPass = "";
3、读取配置文件中的值
/// <summary>
/// 一次性读取配置文件
/// </summary>
public static void LoadConfig()
{
try
{
XmlDocument xml = new XmlDocument();
string xmlfile = GetXMLPath();
if (!File.Exists(xmlfile))
{
throw new Exception("配置文件不存在,路径:" + xmlfile);
}
xml.Load(xmlfile);
string tmpValue = 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 (Exception ex)
{
CConfig.SaveLog("CConfig.LoadConfig() fail,error:" + ex.Message);
Environment.Exit(-1);
}
}
4、配置项的使用
在程序开始时应该调用CConifg.LoadConfig()函数,将所有配置项的值载入到变量中。然后在需要用到配置值的时候,使用CConfig.ConnString即可。
关于C#开发WinForm时使用自定义的XML配置文件,本文就介绍这么多,希望对您有所帮助,谢谢!
要饭二维码
洪哥写文章很苦逼,如果本文对您略有帮助,可以扫描下方二维码支持洪哥!金额随意,先行谢过!大家的支持是我前进的动力!

文章的版权
本文属于“洪哥笔记”原创文章,转载请注明来源地址:C#开发时使用XML配置文件:http://www.splaybow.com/post/csharp-xml-config-file.html
如果您在服务器运维、网络管理、网站或系统开发过程有需要提供收费服务,请加QQ:8771947!十年运维经验,帮您省钱、让您放心!
亲,如果有需要,先存起来,方便以后再看啊!加入收藏夹的话,按Ctrl+D!
发布时间:2014/3/30 9:46:42 | 编辑:洪哥 | 分类:ASP.NET | 浏览: