Replaced hardcoded file paths with a method that retrieves the parent directory, ensuring consistency and maintainability. This change affects methods for loading and saving JSON data in both SettingsData and CustomerData classes.
66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Server.Model;
|
|
|
|
namespace Server.Data
|
|
{
|
|
public class SettingsData
|
|
{
|
|
#region Public Properties
|
|
|
|
public static SettingsData Instance { get; set; } = new();
|
|
|
|
public Address SellerAddress { get; set; } = new();
|
|
|
|
public PaymentData PaymentData { get; set; } = new();
|
|
|
|
public string? Comment { get; set; }
|
|
|
|
#endregion
|
|
|
|
|
|
/// <summary>
|
|
/// Retrieves the file path for the settings JSON file.
|
|
/// </summary>
|
|
/// <returns>The file path of the settings JSON file as a string.</returns>
|
|
private static string GetFilePath()
|
|
{
|
|
var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory());
|
|
if (parentDirectory == null) return "Settings.json";
|
|
|
|
return Path.Combine(parentDirectory.FullName, "Settings.json");
|
|
}
|
|
|
|
#region Public Method Load
|
|
|
|
/// <summary>
|
|
/// Asynchronously loads the settings from a JSON file and updates the current instance of <see cref="SettingsData" />.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous load operation.</returns>
|
|
public static async Task LoadAsync()
|
|
{
|
|
|
|
if (!File.Exists(GetFilePath())) return;
|
|
var jsonString = await File.ReadAllTextAsync(GetFilePath());
|
|
var deserialized = JsonSerializer.Deserialize<SettingsData>(jsonString)!;
|
|
|
|
Instance = deserialized;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Public Method SaveAsync
|
|
|
|
/// <summary>
|
|
/// Serializes the current instance of <see cref="SettingsData" /> and saves it to a JSON file asynchronously.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous save operation.</returns>
|
|
public static async Task SaveAsync()
|
|
{
|
|
var jsonString = JsonSerializer.Serialize(Instance, new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull});
|
|
await File.WriteAllTextAsync(GetFilePath(), jsonString);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |