BDU/ATS/SystemConfig.cs

101 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using ATS.Tools;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
namespace ATS
{
public class SystemConfig
{
private static readonly object _lock = new();
private static SystemConfig? _instance;
public static SystemConfig Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new();
_instance.LoadFromFile();
}
return _instance;
}
}
}
[JsonIgnore]
public string SystemPath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ATS系统");
public int PerformanceLevel { get; set; } = 50;
public string LogFilePath { get; set; } = @"D:\ATS\日志\";
public string DLLFilePath { get; set; } = @"D:\ATS\指令\";
public string SubProgramFilePath { get; set; } = @"D:\ATS\子程序\";
public string PreDefineDevicesPath { get; set; } = @"D:\ATS\设备预设\PreDefineDevices.json";
public string DBCFilePath { get; set; } = @"D:\ATS\DBC文件\ZSDB123500_HY11_HS11_800V_ADCU20_HVEnergeCAN_230901_Fit.dbc";
public string DefaultSubProgramFilePath { get; set; } = "";
// 配置加载方法
public void LoadFromFile()
{
string configPath = Path.Combine(SystemPath, "system.config");
if (!File.Exists(configPath))
{
string json = JsonConvert.SerializeObject(Instance, Formatting.Indented);
File.WriteAllText(configPath, json);
return;
}
try
{
string json = File.ReadAllText(configPath);
var loadedConfig = JsonConvert.DeserializeObject<SystemConfig>(json);
// 复制所有可写属性排除JsonIgnore属性
PropertyInfo[] properties = typeof(SystemConfig).GetProperties();
foreach (var prop in properties)
{
if (prop.CanWrite && !Attribute.IsDefined(prop, typeof(JsonIgnoreAttribute)))
{
prop.SetValue(this, prop.GetValue(loadedConfig));
}
}
}
catch (Exception ex)
{
Log.Error($"配置加载失败: {ex.Message}");
}
}
public void SaveToFile()
{
lock (_lock)
{
try
{
if (!Directory.Exists(SystemPath))
Directory.CreateDirectory(SystemPath);
string configPath = Path.Combine(SystemPath, "system.config");
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(configPath, json);
Log.Info("系统配置已保存。");
}
catch (Exception ex)
{
Log.Error($"配置保存失败: {ex.Message}");
}
}
}
}
}