Config.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using BepInEx.Common;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace BepInEx
  6. {
  7. /// <summary>
  8. /// A helper class to handle persistent data.
  9. /// </summary>
  10. public static class Config
  11. {
  12. private static Dictionary<string, string> cache = new Dictionary<string, string>();
  13. private static string configPath => Path.Combine(Utility.PluginsDirectory, "config.ini");
  14. /// <summary>
  15. /// If enabled, writes the config to disk every time a value is set.
  16. /// </summary>
  17. public static bool SaveOnConfigSet { get; set; } = true;
  18. static Config()
  19. {
  20. if (File.Exists(configPath))
  21. {
  22. ReloadConfig();
  23. }
  24. else
  25. {
  26. SaveConfig();
  27. }
  28. }
  29. /// <summary>
  30. /// Reloads the config from disk. Unwritten changes are lost.
  31. /// </summary>
  32. public static void ReloadConfig()
  33. {
  34. cache.Clear();
  35. foreach (string line in File.ReadAllLines(configPath))
  36. {
  37. string[] split = line.Split('=');
  38. if (split.Length != 2)
  39. continue;
  40. cache[split[0]] = split[1];
  41. }
  42. }
  43. /// <summary>
  44. /// Writes the config to disk.
  45. /// </summary>
  46. public static void SaveConfig()
  47. {
  48. File.WriteAllLines(configPath, cache.Select(x => $"{x.Key}={x.Value}").ToArray());
  49. }
  50. /// <summary>
  51. /// Returns the value of the key if found, otherwise returns the default value.
  52. /// </summary>
  53. /// <param name="key">The key to search for.</param>
  54. /// <param name="defaultValue">The default value to return if the key is not found.</param>
  55. /// <returns>The value of the key.</returns>
  56. public static string GetEntry(string key, string defaultValue)
  57. {
  58. if (cache.TryGetValue(key, out string value))
  59. return value;
  60. else
  61. return defaultValue;
  62. }
  63. /// <summary>
  64. /// Sets the value of the key in the config.
  65. /// </summary>
  66. /// <param name="key">The key to set the value to.</param>
  67. /// <param name="value">The value to set.</param>
  68. public static void SetEntry(string key, string value)
  69. {
  70. cache[key] = value;
  71. if (SaveOnConfigSet)
  72. SaveConfig();
  73. }
  74. }
  75. }