小言_互联网的博客

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

364人阅读  评论(0)

系列文章

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

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

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

C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

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

C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766

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

C#底层库–正则表达式帮助类
本文链接: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#底层库–数据实体类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816638

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/129040663


前言

本专栏为【底层库】,主要介绍编程过程中 通用函数。我们将这些通用固化的源码,进行重写、封装、拓展,再进行单元测试、集成测试、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


转载:https://blog.csdn.net/youcheng_ge/article/details/129175304
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场