using System; using System.IO; using Newtonsoft.Json; using StardewModdingAPI.Advanced; namespace StardewModdingAPI { /// Provides methods for interacting with a mod directory. public class ModHelper { /********* ** 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. public TModel ReadJsonFile(string path) where TModel : class { string fullPath = Path.Combine(this.DirectoryPath, path); TModel model = JsonConvert.DeserializeObject(File.ReadAllText(fullPath)); 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); } } }