源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C# WinForm开发中使用XML配置文件实例

  • 时间:2021-12-23 15:22 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C# WinForm开发中使用XML配置文件实例
本文介绍在使用C#开发WinForm程序时,如何使用自定义的XML配置文件。虽然也可以使用app.config,但命名方面很别扭。 我们在使用C#开发软件程序时,经常需要使用配置文件。虽然说Visual Studio里面也自带了app.config这个种配置文件,但用过的朋友都知道,在编译之后,这个app.config的名称会变成app.程序文件名.config,这多别扭啊!我们还是来自己定义一个配置文件吧。 配置文件就是用来保存一些数据的,那用xml再合适不过。那本文就介绍如何使用XML来作为C#程序的配置文件。 [b]1、创建一个XML配置文件[/b] 比如我们要在配置文件设置一个数据库连接字符串,和一组SMTP发邮件的配置信息,那XML配置文件如下:
[u]复制代码[/u] 代码如下:
<?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@1sucai.cn</smtpuser>   <smtppass>splaybow</smtppass> </root>
熟悉XML的朋友一看就知道是什么意思,也不需要小编多做解释了。 [b]2、设置参数变量来接收配置文件中的值[/b] 创建一个配置类,这个类有很多属性,这些属性对应XML配置文件中的配置项。 假如这个类叫CConfig,那么CConfig.cs中设置如下一组变量:
[u]复制代码[/u] 代码如下:
//数据库配置信息 public static string ConnString = ""; //SMTP发信账号信息 public static string SmtpIp = ""; public static string SmtpUser = ""; public static string SmtpPass = "";
[b]3、读取配置文件中的值[/b]
[u]复制代码[/u] 代码如下:
/// <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);     } }
[b]4、配置项的使用[/b] 在程序开始时应该调用CConifg.LoadConfig()函数,将所有配置项的值载入到变量中。然后在需要用到配置值的时候,使用CConfig.ConnString即可。 关于C#开发WinForm时使用自定义的XML配置文件,本文就介绍这么多,希望对您有所帮助,谢谢!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部