C#底层库--XML配置参数读写辅助类(推荐阅读)

系列文章

C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709

C#底层库–MySQLBuilder脚本构建类(select、insert、update、in、带条件的SQL自动生成)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129179216

C#底层库–MySQL数据库访问操作辅助类(推荐阅读)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–XML配置参数读写辅助类(推荐阅读)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129175304

C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#底层库–FilesHelper文件辅助类(删除目录文件、复制文件到指定目录)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445

C#底层库–随机数生成类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812

C#底层库–RegexHelper正则表达式辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286

C#底层库–CSV和DataTable相互转换
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128804367

C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

C#底层库–JSON帮助类_详细(序列化、反序列化、list、datatable)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805705

C#底层库–cookie操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816347

C#底层库–Session操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817096

C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

C#底层库–数据库类型与程序类型转换类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817610

C#底层库–字符串操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129520428


前言

本专栏为【底层库】,主要介绍编程过程中 通用函数。我们将这些通用固化的源码,进行重写、封装、拓展,再进行单元测试、集成测试、beta测试,最终形成通用化模板,这里我们称为“底层库”。

作为研发人员的你,并不需要花大量时间,研究“底层库”的含义,及“底层库”的实现方法。你只需要几行调用代码,就可以解决项目上碰到的难题。而底层库使用方法,本专栏均有详细介绍,也有项目应用场景。

底层库已实现功能:MySQL脚本构建器、MySQL数据库访问操作、参数配置文件读写、加解密算法、日志记录、HTTP通信、Socket通信、API前后端交互、邮件发送、文件操作、配置参数存储、Excel导入导出、CSV和DataTable转换、压缩解压、自动编号、Session操作等。

本专栏会持续更新,不断优化【底层库】,大家有任何问题,可以私信我,如果你对本栏感兴趣,欢迎关注,我将带你用最简洁的代码实现复杂的功能。
在这里插入图片描述

一、底层库介绍

本文介绍XML配置文件读写,将程序开发中一些可调节变化的参数,以文件形式存储在程序目录中,用户可以自行配置调节,而不需要改动代码。是程序开发中使用频率最高的底层库,所以我强力推荐。

用途:可以实现 数据库连接参数、邮件服务器参数、软件功能参数、服务器连接参数等可以配置。

二、底层库源码

创建类AppConfig,复制以下代码。

using System;
using System.Xml;
using System.IO;

namespace YS_Server
{
    /// <summary>
    /// 全局对象类
    /// 创建人:gyc
    /// 创建事件:2022-03-31
    /// 说明:负责存放配置信息,Server.config。
    /// 使用过程中遇到任何错误,联系作者修改https://blog.csdn.net/youcheng_ge。
    /// </summary>
	public static class AppConfig
    {
        static string InitContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<configuration><appSettings></appSettings></configuration>";

        /// <summary>
        /// 获取Config目录下AppSettings.config中设置的值
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>返回设置值</returns>
        public static string GetValue(string key)
        {
            string configFile = AppDomain.CurrentDomain.BaseDirectory + "Server.config";
            if (!File.Exists(configFile))
            {
                File.WriteAllText(configFile, InitContent);
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(configFile);
                string path = "//add [@key=\"" + key + "\"]/@value";
                XmlNode e = doc.SelectSingleNode(path);
                return e.Value;
            }
            catch
            {
                //throw new Exception("配置文件" + configFile + "中未找到配置项:" + key + ",或者配置项不正确!");
                return "";
            }
        }

        public static string GetValueByPath(string key, string a_strFlPath)
        {
            string configFile = a_strFlPath;
            if (!File.Exists(configFile))
            {
                //				throw new Exception("在目录下未找到配置文件Server.config!");
                return "";
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(configFile);
                string path = "//add [@key=\"" + key + "\"]/@value";
                XmlNode e = doc.SelectSingleNode(path);
                return e.Value;
            }
            catch
            {
                //throw new Exception("配置文件" + configFile + "中未找到配置项:" + key + ",或者配置项不正确!");
                return "";
            }
        }

        public static void SetValue(string key, object value)
        {
            string configFile = AppDomain.CurrentDomain.BaseDirectory + "Server.config";
            XmlDocument doc = new XmlDocument();
            XmlElement l_xSetting;
            if (File.Exists(configFile))
            {
                doc.Load(configFile);
                XmlElement l_root = doc.DocumentElement;
                l_xSetting = l_root.FirstChild as XmlElement;
            }
            else
            {
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                doc.AppendChild(doc.CreateElement("configuration"));
                XmlElement l_root = doc.DocumentElement;
                l_xSetting = doc.CreateElement("appSettings");
                l_root.AppendChild(l_xSetting);
            }
            try
            {
                string path = "//add [@key=\"" + key + "\"]";
                XmlNode e = doc.SelectSingleNode(path);
                if (e == null)
                {
                    XmlElement l_key = doc.CreateElement("add");
                    l_key.SetAttribute("key", key);
                    l_key.SetAttribute("value", value.ToString());
                    l_xSetting.AppendChild(l_key);
                }
                else
                {
                    XmlElement l_key = e as XmlElement;
                    l_key.SetAttribute("key", key);
                    l_key.SetAttribute("value", value.ToString());
                }
            }
            finally
            {
                doc.Save(configFile);
            }
        }

        /// <summary>
        /// 获取Config目录下AppSettings.config中设置的值
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="valueDefault">默认值</param>
        /// <returns>返回设置值,如果没有设置则返回默认值</returns>
        public static string GetValue(string key, string valueDefault)
        {
            string result = "";
            try
            {
                result = AppConfig.GetValue(key);
            }
            catch
            {
            }
            if (result == "")
                return valueDefault;
            else
                return result;
        }
    }
}

三、调用方法

调用方法是很简单的,分为两部分,写参数 和 读参数

3.1 写参数

写参数,这是我以前项目用的,写 自动邮件发送参数、自动关机参数等。

   //写入配置文件
   AppConfig.SetValue("res_path", this.BTN_ResPath.Text);
   //AppConfig.SetValue("auto_run", this.checkBox_AutoRun.Checked ? "T" : "F");
   //AppConfig.SetValue("shutdown_tag", this.RB_ShutDownYes.Checked ? "T" : "F");
   //AppConfig.SetValue("shutdown_time", this.tp_ShutDownTime.Value);
   AppConfig.SetValue("max_runtime", this.NUD_MaxRunTime.Value);
   AppConfig.SetValue("fullscreen_time", this.NUD_FullScreenTime.Value);
   AppConfig.SetValue("exit_time", this.NUD_ExitTime.Value);
   AppConfig.SetValue("mail_server", this.txt_MailServer.Text);
   AppConfig.SetValue("mail_send", this.txt_MailSend.Text);
   AppConfig.SetValue("mail_password", this.txt_MailPwd.Text);
   AppConfig.SetValue("mail_receive", this.txt_MailReceive.Text);
   AppConfig.SetValue("send_time", this.tp_SendTime.Value);
   string l_strMedia = AppDomain.CurrentDomain.BaseDirectory + Const.ct_strPlayerName;
   AppConfig.SetValue("media_path", l_strMedia);
   AppConfig.SetValue("timer_interval", 5000);

3.2 读参数

读取数据库连接参数:ip地址、端口号、数据库名、用户名、密码。

    /// <summary>
    /// 构造函数
    /// </summary>
    public MySQLHelper()
    {
        this.server = AppConfig.GetValue("db_server");
        this.port = AppConfig.GetValue("db_port");
        this.BaseName = AppConfig.GetValue("db_base");
        this.uid = AppConfig.GetValue("db_uid");
        this.pwd = AppConfig.GetValue("db_pwd");
        //MySQL.Data 8.0.28.0
        //this.connectionString = $"server={server};port={port};user id={uid};password={pwd};database={BaseName};pooling=true;ConnectionTimeout=1800;CharSet=utf8";
        //MySQL.Data 8.0.26.0
        this.connectionString = $"server={server};port={port};uid={uid};pwd={pwd};database={BaseName};SslMode=None;Charset=utf8";
    }

四、项目案例

用于数据库连接串配置,我的所有文章,均使用本底层库,将数据库连接参数可配置化。相关文章如下:

C#底层库–MySQL数据库访问操作辅助类(推荐阅读)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–数据库类型与程序类型转换类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817610

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花北城

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值