仿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(); // 保存
相关推荐
hez20103 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
Venuslite5 天前
从 Unexpected token < 到 Extra data:一次讲清 JSON 解析错误的排查思路
json
雨落倾城夏未凉8 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫9 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫10 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62510 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021110 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠11 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
疯狂SQL11 天前
手写高性能在线 JSON 工具|Web Worker 工程化打包 + 语法自动修复 + 多语言代码生成实战
typescript·json·next.js·web worker·前端性能优化·esbuild·源码实战
唐青枫13 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net