/// <summary> /// Writes all values to the config file. If the config file does not /// exist, it gets created, along with all the directories involved. /// An existing file will get overwritten. /// </summary> public static void SaveConfig() { var options = new JsonSerializerOptions { WriteIndented = true }; if (_model == null) { _model = new PathConfModel(); } Directory.CreateDirectory(Path.GetDirectoryName(ConfFile)); string serialized = JsonSerializer.Serialize(_model, _model.GetType(), options); File.WriteAllText(ConfFile, serialized); // Because in Linux "Root Owns Everything", we need to change the owner of the // config back to our current user if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && SystemAndShellUtils.IsAdmin()) { var user = SystemAndShellUtils.GetCurrentUser(); _shell.Term($"chown {user} {ConfFile}"); _shell.Term($"chown {user} {Path.GetDirectoryName(ConfFile)}"); } }
/// <summary> /// Reads all values from the config file. If the config file does not /// exist, all config properties will have their default value. /// </summary> public static void LoadConfig() { // In no config file exists, "loading" shall reset the config to // default values. We achieve this by simply creating a new model. _model = new PathConfModel(); // If no config file exists, we're done if (!File.Exists(ConfFile)) { return; } // Try loading the values from file try { using (JsonDocument document = JsonDocument.Parse(File.ReadAllText(ConfFile))) { JsonElement value; if (document.RootElement.TryGetProperty(nameof(_model.ClientInstallPath), out value)) { _model.ClientInstallPath = value.GetString(); } if (document.RootElement.TryGetProperty(nameof(_model.ClientDBPath), out value)) { _model.ClientDBPath = value.GetString(); } if (document.RootElement.TryGetProperty(nameof(_model.LogPath), out value)) { _model.LogPath = value.GetString(); } } } catch (Exception ex) { Log.Error($"Error deserializing path config file:\r\n{ex}"); } finally { if (_model == null) { _model = new PathConfModel(); } // Sanitize loaded values if (string.IsNullOrEmpty(_model.ClientInstallPath)) { _model.ClientInstallPath = DefaultClientInstallPath; } if (string.IsNullOrEmpty(_model.ClientDBPath)) { _model.ClientDBPath = DefaultClientDBPath; } if (string.IsNullOrEmpty(_model.LogPath)) { _model.LogPath = DefaultLogPath; } // Since loading may have sanitized or amended new values, we // save the config here to that changes are written back to file. SaveConfig(); } }