Files
AetherBags/AetherBags/Helpers/JsonFileHelper.cs
T
2025-12-24 19:50:11 +01:00

71 lines
2.3 KiB
C#

using System;
using System.IO;
using System.Text.Json;
using Dalamud.Utility;
namespace AetherBags.Helpers;
public static class JsonFileHelper {
private static readonly JsonSerializerOptions SerializerOptions = new() {
WriteIndented = true,
IncludeFields = true,
};
public static T LoadFile<T>(string filePath) where T : new() {
var fileInfo = new FileInfo(filePath);
if (fileInfo is { Exists: true }) {
try {
var fileText = File.ReadAllText(fileInfo.FullName);
var dataObject = JsonSerializer.Deserialize<T>(fileText, SerializerOptions);
// If deserialize result is null, create a new instance instead and save it.
if (dataObject is null) {
dataObject = new T();
SaveFile(dataObject, filePath);
}
return dataObject;
}
catch (Exception e) {
// If there is any kind of error loading the file, generate a new one instead and save it.
Services.Logger.Error(e, $"Error trying to load file {filePath}, creating a new one instead.");
SaveFile(new T(), filePath);
}
}
var newFile = new T();
SaveFile(newFile, filePath);
return newFile;
}
public static void SaveFile<T>(T? file, string filePath) {
try {
if (file is null) {
Services.Logger.Error("Null file provided.");
return;
}
var fileText = JsonSerializer.Serialize(file, file.GetType(), SerializerOptions);
FilesystemUtil.WriteAllTextSafe(filePath, fileText);
}
catch (Exception e) {
Services.Logger.Error(e, $"Error trying to save file {filePath}");
}
}
public static FileInfo GetFileInfo(params string[] path) {
var directory = Services.PluginInterface.ConfigDirectory;
for (var index = 0; index < path.Length - 1; index++) {
directory = new DirectoryInfo(Path.Combine(directory.FullName, path[index]));
if (!directory.Exists) {
directory.Create();
}
}
return new FileInfo(Path.Combine(directory.FullName, path[^1]));
}
}