using BepInEx.Common; using System.Collections.Generic; using System.IO; using System.Linq; namespace BepInEx { /// /// A helper class to handle persistent data. /// public static class Config { private static Dictionary> cache = new Dictionary>(); private static string configPath => Path.Combine(Utility.PluginsDirectory, "config.ini"); /// /// If enabled, writes the config to disk every time a value is set. /// public static bool SaveOnConfigSet { get; set; } = true; static Config() { if (File.Exists(configPath)) { ReloadConfig(); } else { SaveConfig(); } } /// /// Reloads the config from disk. Unwritten changes are lost. /// public static void ReloadConfig() { cache.Clear(); string currentSection = ""; foreach (string rawLine in File.ReadAllLines(configPath)) { string line = rawLine.Trim(); int commentIndex = line.IndexOf("//"); if (commentIndex != -1) //trim comment line = line.Remove(commentIndex); if (line.StartsWith("[") && line.EndsWith("]")) //section { currentSection = line.Substring(1, line.Length - 2); continue; } string[] split = line.Split('='); //actual config line if (split.Length != 2) continue; //empty/invalid line if (!cache.ContainsKey(currentSection)) cache[currentSection] = new Dictionary(); cache[currentSection][split[0]] = split[1]; } } /// /// Writes the config to disk. /// public static void SaveConfig() { using (StreamWriter writer = new StreamWriter(File.Create(configPath), System.Text.Encoding.UTF8)) foreach (var sectionKv in cache) { writer.WriteLine($"[{sectionKv.Key}]"); foreach (var entryKv in sectionKv.Value) writer.WriteLine($"{entryKv.Key}={entryKv.Value}"); writer.WriteLine(); } } /// /// Returns the value of the key if found, otherwise returns the default value. /// /// The key to search for. /// The default value to return if the key is not found. /// The value of the key. public static string GetEntry(string key, string defaultValue = "", string section = "") { if (section.IsNullOrWhiteSpace()) section = "Global"; Dictionary subdict; if (!cache.TryGetValue(section, out subdict)) return defaultValue; if (subdict.TryGetValue(key, out string value)) return value; else return defaultValue; } /// /// Sets the value of the key in the config. /// /// The key to set the value to. /// The value to set. public static void SetEntry(string key, string value, string section = "") { if (section.IsNullOrWhiteSpace()) section = "Global"; Dictionary subdict; if (!cache.TryGetValue(section, out subdict)) { subdict = new Dictionary(); cache[section] = subdict; } subdict[key] = value; if (SaveOnConfigSet) SaveConfig(); } #region Extensions public static string GetEntry(this BaseUnityPlugin plugin, string key, string defaultValue = "") { return GetEntry(key, defaultValue, plugin.ID); } public static void SetEntry(this BaseUnityPlugin plugin, string key, string value) { SetEntry(key, value, plugin.ID); } #endregion } }