DHDHSoftware/DHSoftware/Utils/ConfigManager.cs
2025-03-18 14:19:33 +08:00

155 lines
4.8 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Windows.Forms;
using DH.Commons.Enums;
using DH.Devices.Devices;
using DH.Devices.PLC;
namespace DH.Commons.Helper
{
// 配置数据模型
public class AppConfig
{
public List<CameraBase> Cameras { get; set; } = new List<CameraBase>();
public List<PLCBase> PLCs { get; set; } = new List<PLCBase>();
public List<DetectionConfig> Detections { get; set; } = new List<DetectionConfig>();
}
// 配置管理工具类
public static class ConfigManager
{
private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
IgnoreNullValues = true
};
// 默认路径配置
private static readonly string DefaultConfigDir = Path.Combine(
Application.StartupPath,
"configs"
);
public static readonly string DefaultConfigPath = Path.Combine(
DefaultConfigDir,
"appsettings.json"
);
/// <summary>
/// 保存配置文件(自动处理目录和备份)
/// </summary>
/// <param name="config">配置对象</param>
/// <param name="filePath">可选文件路径</param>
public static void SaveConfig(AppConfig config, string filePath = null)
{
try
{
// 使用默认路径如果未指定
filePath ??= DefaultConfigPath;
// 确保配置目录存在
var configDir = Path.GetDirectoryName(filePath);
if (!Directory.Exists(configDir))
{
Directory.CreateDirectory(configDir);
}
// 备份已有配置
if (File.Exists(filePath))
{
BackupConfig(filePath);
}
// 序列化并保存
string json = JsonSerializer.Serialize(config, _jsonOptions);
File.WriteAllText(filePath, json);
}
catch (Exception ex)
{
throw new InvalidOperationException("配置保存失败", ex);
}
}
/// <summary>
/// 加载配置文件
/// </summary>
/// <param name="filePath">可选文件路径</param>
/// <returns>配置对象</returns>
public static AppConfig LoadConfig(string filePath = null)
{
try
{
filePath ??= DefaultConfigPath;
if (!File.Exists(filePath))
{
return new AppConfig(); // 返回空配置而不是null
}
string json = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<AppConfig>(json, _jsonOptions);
}
catch (Exception ex)
{
throw new InvalidOperationException("配置加载失败", ex);
}
}
/// <summary>
/// 创建带时间戳的备份文件
/// </summary>
private static void BackupConfig(string originalPath)
{
try
{
// 创建备份目录
var backupDir = Path.Combine(
Path.GetDirectoryName(originalPath),
"backups"
);
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
// 生成带时间戳的文件名
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string fileName = $"{Path.GetFileNameWithoutExtension(originalPath)}_" +
$"{timestamp}" +
$"{Path.GetExtension(originalPath)}";
// 执行备份
File.Copy(
originalPath,
Path.Combine(backupDir, fileName),
overwrite: true
);
}
catch (Exception ex)
{
throw new InvalidOperationException("配置备份失败", ex);
}
}
/// <summary>
/// 创建新的配置对象
/// </summary>
public static AppConfig CreateConfig(
List<CameraBase> cameras = null,
List<PLCBase> plcs = null,
List<DetectionConfig> detections = null)
{
return new AppConfig
{
Cameras = cameras ?? new List<CameraBase>(),
PLCs = plcs ?? new List<PLCBase>(),
Detections = detections ?? new List<DetectionConfig>()
};
}
}
}