using System; using System.IO; using Newtonsoft.Json; using StardewModdingAPI.Advanced; namespace StardewModdingAPI { /// Provides methods for interacting with a mod directory. [Obsolete("Use " + nameof(IModHelper) + " instead.")] public class ModHelper : IModHelper { /********* ** Accessors *********/ /// The mod directory path. public string DirectoryPath { get; } /********* ** Public methods *********/ /// Construct an instance. /// The mod directory path. public ModHelper(string modDirectory) { // validate if (string.IsNullOrWhiteSpace(modDirectory)) throw new InvalidOperationException("The mod directory cannot be empty."); if (!Directory.Exists(modDirectory)) throw new InvalidOperationException("The specified mod directory does not exist."); // initialise this.DirectoryPath = modDirectory; } /**** ** Mod config file ****/ /// Read the mod's configuration file (and create it if needed). /// The config class type. This should be a plain class that has public properties for the settings you want. These can be complex types. public TConfig ReadConfig() where TConfig : class, new() { var config = this.ReadJsonFile("config.json") ?? new TConfig(); this.WriteConfig(config); // create file or fill in missing fields return config; } /// Save to the mod's configuration file. /// The config class type. /// The config settings to save. public void WriteConfig(TConfig config) where TConfig : class, new() { this.WriteJsonFile("config.json", config); } /**** ** Generic JSON files ****/ /// Read a JSON file. /// The model type. /// The file path relative to the mod directory. /// Returns the deserialised model, or null if the file doesn't exist or is empty. public TModel ReadJsonFile(string path) where TModel : class { // read file string fullPath = Path.Combine(this.DirectoryPath, path); string json; try { json = File.ReadAllText(fullPath); } catch (FileNotFoundException) { return null; } // deserialise model TModel model = JsonConvert.DeserializeObject(json); if (model is IConfigFile) { var wrapper = (IConfigFile)model; wrapper.ModHelper = this; wrapper.FilePath = path; } return model; } /// Save to a JSON file. /// The model type. /// The file path relative to the mod directory. /// The model to save. public void WriteJsonFile(string path, TModel model) where TModel : class { path = Path.Combine(this.DirectoryPath, path); // create directory if needed string dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // write file string json = JsonConvert.SerializeObject(model, Formatting.Indented); File.WriteAllText(path, json); } } }