仿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(); // 保存
相关推荐
鲸渔9 小时前
【AI Agent系列课程13-Python 基础13】JSON 读写:结构化数据交换基础
开发语言·python·json·ai编程
zdr尽职尽责2 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
aiotto资源分享3 天前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
BruceNeter3 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
一起学安全技术4 天前
拆大模型 10|结构化输出:让模型返回数据,而不是一段话
人工智能·语言模型·json
用户298698530144 天前
在 Python 中把 Word 文档转换为 JSON 的三种实现方式
python·json·api
何以解忧唯有撸码5 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手5 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库6 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc6 天前
C# 发展历史
开发语言·c#