核心实现类
/// <summary>
/// JSON配置服务
/// 支持实体类序列化保存
/// </summary>
public class JsonConfigService
{
private static readonly object fileLock = new object();
private const string DefaultFilePath = "config.json";
/// <summary>
/// 保存配置实体
/// </summary>
/// <typeparam name="T">配置类型</typeparam>
/// <param name="config">配置对象</param>
/// <param name="filePath">文件路径</param>
public void Save<T>( T config, string filePath = DefaultFilePath)
{
lock (fileLock)
{
EnsureDirectory(filePath);
string json = JsonConvert.SerializeObject( config, Formatting.Indented);
File.WriteAllText( filePath, json);
}
}
/// <summary>
/// 读取配置实体
/// </summary>
/// <typeparam name="T">
/// 配置类型
/// </typeparam>
/// <param name="defaultConfig">
/// 默认配置
/// </param>
public T Load<T>(T defaultConfig = default, string filePath = DefaultFilePath)
{
lock (fileLock)
{
if (!File.Exists(filePath))
{
Save( defaultConfig, filePath);
return defaultConfig;
}
try
{
string json = File.ReadAllText(filePath);
T config = JsonConvert.DeserializeObject<T>(json);
if (config == null)
{
return defaultConfig;
}
return config;
}
catch
{
// 文件损坏时恢复默认
Save( defaultConfig, filePath);
return defaultConfig;
}
}
}
/// <summary>
/// 更新配置中的某个属性
/// </summary>
public void Update<T>( Action<T> action, T defaultConfig = default, string filePath = DefaultFilePath)
{
lock (fileLock)
{
T config = Load( defaultConfig, filePath);
action(config);
Save(config, filePath);
}
}
/// <summary>
/// 判断文件并创建目录
/// </summary>
private void EnsureDirectory(string filePath)
{
string dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
实体类
/// <summary>
/// 参数配置
/// </summary>
public class ConfigParaModel
{
/// <summary>
/// 串口
/// </summary>
public string COM { get; set; }
/// <summary>
/// 接口信息
/// </summary>
public StateGridInterfaceModel StateGrid { get; set; } = new StateGridInterfaceModel();
}
public class StateGridInterfaceModel
{
public string IP { get; set; }
public int Port { get; set; }
}
方法的调用
保存配置
var configService = new JsonConfigService();
ConfigParaModel config = new ConfigParaModel()
{
COM = "COM3",
StateGrid = new StateGridInterfaceModel()
{
IP="192.168.1.10",
Port=8080
}
};
configService.Save(config);读取配置
ConfigParaModel config =
configService.Load(
new ConfigParaModel()
{
COM="COM1"
});修改一个参数
configService.Update<ConfigParaModel>(
cfg =>
{
cfg.COM="COM5";
});