Files
SzmediTools/BoreholeExtract/ConfigService.cs
2025-12-23 21:37:02 +08:00

44 lines
1.3 KiB
C#
Raw Permalink 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 System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace BoreholeExtract
{
public class ConfigService
{
private const string FileName = "config.json";
// 加载配置
public List<CategoryConfig> LoadConfig()
{
if (!File.Exists(FileName)) return new List<CategoryConfig>();
try
{
var json = File.ReadAllText(FileName);
// 使用 Newtonsoft 反序列化
// 即使 JSON 格式稍微有点错比如多了个逗号Newtonsoft 通常也能兼容
var result = JsonConvert.DeserializeObject<List<CategoryConfig>>(json);
return result ?? new List<CategoryConfig>();
}
catch
{
// 文件损坏或格式错误,返回空列表,稍后逻辑会填充默认值
return new List<CategoryConfig>();
}
}
// 保存配置
public void SaveConfig(IEnumerable<CategoryConfig> configs)
{
// 设置格式化选项:缩进排版,方便人眼阅读
var json = JsonConvert.SerializeObject(configs, Formatting.Indented);
File.WriteAllText(FileName, json);
}
}
}