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

前端技术 2023/09/04 C#

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

本文地址:https://www.stayed.cn/item/9624

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。