仿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(); // 保存
相关推荐
剩下了什么12 小时前
MySQL JSON_SET() 函数
数据库·mysql·json
bugcome_com13 小时前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗17 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
梦帮科技17 小时前
Node.js配置生成器CLI工具开发实战
前端·人工智能·windows·前端框架·node.js·json
缺点内向18 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟19 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_9307077819 小时前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏20 小时前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
大空大地202621 小时前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
数据知道1 天前
PostgreSQL实战:详解如何用Python优雅地从PG中存取处理JSON
python·postgresql·json