仿NewLife的XmlConfig类实现Json配置文件

学习NewLife的配置类XmlConfig实现的边界配置文件读写类

UserProfile

csharp 复制代码
using System;
using System.IO;
using System.Reflection;

namespace HeBingSQL
{
    /* 使用示例
    [ConfigFile(".hebingsql")]
    public class AppConfig : UserProfile<AppConfig >
    {
        public bool AutoStart { get; set; } = true;
    }
    */
    /// <summary>
    /// 把配置文件保存到用户目录下的通用配置基类
    /// </summary>
    /// <typeparam name="T">业务配置类</typeparam>
    public class UserProfile<T> where T : new()
    {
        public static T _current;

        private static string ConfigFilePath
        {
            get
            {
                var attr = typeof(T).GetCustomAttribute<ConfigFileAttribute>();
                var fileName = attr?.FileName ?? ".defaultuncleconfig";
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), fileName);
            }
        }

        protected UserProfile()
        {
        }

        public static T Current
        {
            get
            {
                if (_current == null)
                {
                    _current = Load();
                }
                return _current;
            }
        }

        public static T Load()
        {
            // 获取系统用户目录并设置配置文件路径
            string config = "";
            if (File.Exists(ConfigFilePath))
            {
                // 从配置文件中读取快捷方式
                config = File.ReadAllText(ConfigFilePath);
                return System.Text.Json.JsonSerializer.Deserialize<T>(config);
            }
            else
            {
                // 创建默认配置文件
                var obj = new T();
                string jsonString = System.Text.Json.JsonSerializer.Serialize(obj);
                File.WriteAllText(ConfigFilePath, jsonString);

                return obj;
            }
        }
        public void Save()
        {
            // 保存配置到文件的逻辑
            // 这里可以使用序列化库将当前对象保存为XML或JSON格式
            string jsonString = System.Text.Json.JsonSerializer.Serialize(_current);
            File.WriteAllText(ConfigFilePath, jsonString);
        }
    }

	// 读取配置文件名的特性类
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class ConfigFileAttribute : Attribute
    {
        public string FileName { get; private set; }

        public ConfigFileAttribute(string fileName)
        {
            FileName = fileName;
        }
    }
}

使用

1,新增一个APP的配置类

csharp 复制代码
[ConfigFile(".hebingsql")]
public class AppConfig : UserProfile<AppConfig>
{
    public bool AutoStart { get; set; } = true;
}

2,使用

csharp 复制代码
var tmp = MyConfig.Current.AutoStart; // 读取
MyConfig.Current.AutoStart = false; // 赋值
MyConfig.Current.Save(); // 保存
相关推荐
伞伞悦读2 小时前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
Mikko72 小时前
jackson-databind 升到 2.21.6 就安全了吗?jackson-core 是另一个坐标,它那条 high 全局库至今没收
java·后端·安全·json
Polevne4 小时前
C# SFTP客户端实现文件传输
c#·ssh
samble4 小时前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5605 小时前
024 . WPF MVVM类封装优化
c#
淡海水16 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx6717 小时前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707781 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码1 天前
【开源】c#造个轮子-日程安排工具
c#·自定义控件
周杰伦fans1 天前
CAD菜单栏和工具栏都不见了,怎么显示?
其他·c#