41 lines
1.6 KiB
C#
41 lines
1.6 KiB
C#
using System.IO;
|
|
using System.Text.Json;
|
|
|
|
namespace Hk4eGm.Services;
|
|
|
|
public sealed class Templates
|
|
{
|
|
public static string MailPath => Path.Combine(AppConfig.AppDir, "MailTemplate.json");
|
|
public static string CmdPath => Path.Combine(AppConfig.AppDir, "CmdTemplate.json");
|
|
|
|
public static List<Dictionary<string, JsonElement>> LoadMail() => Load(MailPath);
|
|
public static void SaveMail(List<Dictionary<string, JsonElement>> items) => Save(MailPath, items);
|
|
public static List<Dictionary<string, JsonElement>> LoadCmd() => Load(CmdPath);
|
|
public static void SaveCmd(List<Dictionary<string, JsonElement>> items) => Save(CmdPath, items);
|
|
|
|
private static List<Dictionary<string, JsonElement>> Load(string path)
|
|
{
|
|
if (!File.Exists(path)) return new();
|
|
try
|
|
{
|
|
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
|
if (doc.RootElement.ValueKind != JsonValueKind.Array) return new();
|
|
return doc.RootElement.EnumerateArray()
|
|
.Where(x => x.ValueKind == JsonValueKind.Object)
|
|
.Select(x => x.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.Clone()))
|
|
.ToList();
|
|
}
|
|
catch
|
|
{
|
|
return new();
|
|
}
|
|
}
|
|
|
|
private static void Save(string path, List<Dictionary<string, JsonElement>> items)
|
|
=> File.WriteAllText(path, JsonSerializer.Serialize(items, new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
|
}));
|
|
}
|