C#简易配置读写类
in 默认分类 with 0 comment
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
/**
1.初始化配置实例
// 获取 app_config.json 配置文件的实例
Config config = Config.GetInstance("app_config");

2.设置配置项
// 设置一个配置项(键值对)
config.Set("sitename", "MyAwesomeSite");

// 设置一个复杂类型的配置项(例如:数组或字典)
config.Set("user", new { name = "Peter", age = 30 });

3.获取配置项
// 获取一个配置项的值,如果没有找到,返回默认值
string siteName = (string)config.Get("sitename", "DefaultSiteName");
var user = config.Get("user", new { name = "Unknown", age = 0 });
Console.WriteLine($"User Name: {user.name}, Age: {user.age}");

4.删除配置项
// 删除指定的配置项
config.Delete("user");

5.保存配置文件
// 保存配置项到文件
bool success = config.Save();
if (success) {
    Console.WriteLine("Config saved successfully.");
} else {
    Console.WriteLine("Failed to save config.");
}
*/
internal class Config
{
    private static readonly ConcurrentDictionary<string, Lazy<Config>> Instances = new();
    private readonly ConcurrentDictionary<string, object> _data;
    private readonly string _file;

    private Config(string file)
    {
        _file = file + ".json";
        var directory = Path.GetDirectoryName(_file) ?? Directory.GetCurrentDirectory();
        if (!Directory.Exists(directory)) {
            Directory.CreateDirectory(directory);
        }
        _data = Read();
    }

    private ConcurrentDictionary<string, object> Read()
    {
        if (!File.Exists(_file)) return new ConcurrentDictionary<string, object>();
        var json = File.ReadAllText(_file);
        var data = JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new Dictionary<string, object>();
        return new ConcurrentDictionary<string, object>(data);
    }

    public object Get(string key, object defaultValue = null)
    {
        return _data.TryGetValue(key, out var value) ? value : defaultValue;
    }

    public Config Set(string key, object value)
    {
        _data[key] = value;
        return this;
    }

    public Config Delete(string key)
    {
        _data.TryRemove(key, out _);
        return this;
    }

    public bool Save()
    {
        try {
            var json = JsonSerializer.Serialize(_data, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(_file, json);
            return true;
        } catch (Exception ex) {
            Console.WriteLine("Save error: " + ex.Message);
            return false;
        }
    }

    public static Config GetInstance(string file)
    {
        // 使用 Lazy 来确保 Config 实例的延迟初始化且线程安全
        return Instances.GetOrAdd(file, f => new Lazy<Config>(() => new Config(f))).Value;
    }
}
回复