From 2793b94040a473538f01723d5ca5f53c4535e2af Mon Sep 17 00:00:00 2001 From: Sarah Bradley Date: Fri, 1 Dec 2023 20:33:42 -0800 Subject: What I've got so far --- ConfigFile.cs | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 ConfigFile.cs (limited to 'ConfigFile.cs') diff --git a/ConfigFile.cs b/ConfigFile.cs new file mode 100644 index 0000000..e0f1293 --- /dev/null +++ b/ConfigFile.cs @@ -0,0 +1,84 @@ +namespace OnekoOnline; + +class ConfigFile +{ + public readonly string Path; + readonly Dictionary ConfigOptions = []; + bool OptionChanged = false; + const string TopLine = "# OnekoOnline Config File"; + + public ConfigFile(string path) + { + Path = path; + + if (!File.Exists(Path)) { + Console.WriteLine("Config file does not exist, creating one."); + File.WriteAllText(Path, TopLine); + OptionChanged = true; + return; + } + + string[] fileContents = File.ReadAllLines(Path); + + foreach (string line in fileContents) { + if (line[0] == '#' || !line.Contains('=') || line.Length < 3) continue; + + string key = line[0..line.IndexOf('=')]; + string value = line[(line.IndexOf('=')+1)..]; + ConfigOptions.Add(key, value); + } + } + + public void SaveFile() + { + if (!OptionChanged) return; + + List linesToWrite = [TopLine]; + foreach (KeyValuePair pair in ConfigOptions.OrderBy(k => k.Key)) linesToWrite.Add(pair.Key + "=" + pair.Value); + File.WriteAllLines(Path, linesToWrite); + + OptionChanged = false; + } + + public T GetValue(string Key, T defaultValue) where T : IConvertible + { + if (ConfigOptions.TryGetValue(Key, out string? value)) { + try { + return (T)Convert.ChangeType(value, typeof(T)); + } catch { + Console.WriteLine($"Config option {Key} is invalid, setting to default."); + } + } + + SetValue(Key, defaultValue); + return defaultValue; + } + + public string GetValue(string Key, string defaultValue) + { + if (ConfigOptions.TryGetValue(Key, out string? value)) { + return value; + } + + SetValue(Key, defaultValue); + return defaultValue; + } + + public void SetValue(string Key, T Value) where T : IConvertible + { + string? ValueString = Value.ToString(); + if (ValueString is null) return; + + SetValue(Key, ValueString); + } + + public void SetValue(string Key, string Value) + { + if (ConfigOptions.TryAdd(Key, Value)) { + OptionChanged = true; + } else if (ConfigOptions[Key] != Value) { + ConfigOptions[Key] = Value; + OptionChanged = true; + } + } +} \ No newline at end of file -- cgit