internal static void LoadAddonSavedValues(string addonId) { // Check if values have already been loaded if (SavedValues.ContainsKey(addonId)) { return; } // Create a new entry SavedValues.Add(addonId, new Dictionary <string, List <Dictionary <string, object> > >()); // Verify that the directory exists Directory.CreateDirectory(SaveDataDirectoryPath); // Get the file path var filePath = Path.Combine(SaveDataDirectoryPath, addonId + ".json"); // Check if save file exists if (!File.Exists(filePath)) { return; } // Deserialize file contents var data = JsonConvert.DeserializeObject <Dictionary <string, List <Dictionary <string, object> > > >(File.ReadAllText(filePath)); // Apply saved data to dictionary SavedValues[addonId] = data; }
internal static void OnSaveTimerElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { // Verify that the directory exists Directory.CreateDirectory(SaveDataDirectoryPath); foreach (var entry in MenuInstances) { // Serialize current data var data = new Dictionary <string, List <Dictionary <string, object> > >(); foreach (var menu in entry.Value) { data[menu.UniqueMenuId] = menu.ValueContainer.Serialize(); } // Verify that there is data to save if (data.Count > 0) { // Merge previous data with current data var dataToSave = SavedValues.ContainsKey(entry.Key) ? SavedValues[entry.Key] : new Dictionary <string, List <Dictionary <string, object> > >(); foreach (var entryKeys in data) { dataToSave[entryKeys.Key] = entryKeys.Value; } // Get the file path var filePath = Path.Combine(SaveDataDirectoryPath, entry.Key + ".json"); var fileBackupPath = filePath + ".backup"; // Create a backup of the current file if (File.Exists(filePath)) { File.Copy(filePath, fileBackupPath, true); } try { // Write content to the file File.WriteAllText(filePath, JsonConvert.SerializeObject(dataToSave)); } catch (Exception e) { // Restore the backup if (File.Exists(fileBackupPath)) { Logger.Warn("Error during config file writing, restoring backup!"); File.Copy(fileBackupPath, filePath, true); } } // Delete the backup file File.Delete(fileBackupPath); } } }