欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-06-24 08:19:24|栏目:.NET代码|点击:

本文介绍在使用C#开发WinForm程序时,如何使用自定义的XML配置文件。虽然也可以使用app.config,但命名方面很别扭。

我们在使用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@jb51.net</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配置文件,本文就介绍这么多,希望对您有所帮助,谢谢!

上一篇:window.showModalDialog两次加载问题清除缓存方法

栏    目:.NET代码

下一篇:Json数据转换list对象实现思路及代码

本文标题:C# WinForm开发中使用XML配置文件实例

本文地址:http://www.codeinn.net/misctech/147321.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有