using Newtonsoft.Json; using System; using System.IO;

namespace SongManager { public class Locations { // Singleton design pattern private static Locations locations = null;

    public string toBeDownloadedLocation = "";
    public string toBeRemovedLocation = "";
    public string toBeUpdatedLocation = "";
    public string logLocation = "";

    public static string settingsDirectory = Environment.CurrentDirectory.ToString();
    public static string locationsSettings = "";

    /// <summary>
    /// Private constructor for the Singleton pattern.
    /// </summary>
    private Locations() { }

    /// <summary>
    /// Gets the instance of the Locations class.
    /// </summary>
    /// <returns>The instance of the Locations class.</returns>
    public static Locations GetLocations()
    {
        if (locations == null)
        {
            locations = new Locations();
        }
        return locations;
    }

    /// <summary>
    /// Loads locations from the settings file.
    /// </summary>
    public static void LoadLocations()
    {
        try
        {
            locationsSettings = File.ReadAllText(settingsDirectory + "\settings.txt");
        }
        catch (FileNotFoundException ex)
        {
            File.WriteAllText(settingsDirectory + "\settings.txt", "");
        }
        locations = JsonConvert.DeserializeObject<Locations>(locationsSettings);
    }

    /// <summary>
    /// Saves locations to the settings file.
    /// </summary>
    public static void SaveLocations()
    {
        locationsSettings = JsonConvert.SerializeObject(locations);
        File.WriteAllText(settingsDirectory + "\settings.txt", locationsSettings);
    }

    /// <summary>
    /// Updates locations and saves them to the settings file.
    /// </summary>
    /// <param name="toBeDownloadedLocation">The path to the location to be downloaded.</param>
    /// <param name="toBeRemovedLocation">The path to the location to be removed.</param>
    /// <param name="toBeUpdatedLocation">The path to the location to be updated.</param>
    /// <param name="logLocation">The path to the log file.</param>
    public static void UpdateLocations(string toBeDownloadedLocation, string toBeRemovedLocation, string toBeUpdatedLocation, string logLocation)
    {
        locations.toBeDownloadedLocation = toBeDownloadedLocation;
        locations.toBeRemovedLocation = toBeRemovedLocation;
        locations.toBeUpdatedLocation = toBeUpdatedLocation;
        locations.logLocation = logLocation;
        SaveLocations();
    }
}

}

C# Singleton Pattern with File Persistence using Newtonsoft.Json

原文地址: https://www.cveoy.top/t/topic/Eyt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录