/// <summary> /// Saves an object to a file, optionally keeping a backup of it. /// </summary> /// <param name="toSave">Object to save as a file.</param> /// <param name="fileName">Name of the file to be saved.</param> /// <param name="options">The serialization options.</param> public void SaveToFile(T toSave, string fileName, FileStorageOption options = null) { Guard.NotEmpty(fileName, nameof(fileName)); Guard.NotNull(toSave, nameof(toSave)); if (options == null) { options = FileStorageOption.Default; } string filePath = Path.Combine(this.FolderPath, fileName); long uniqueId = DateTime.UtcNow.Ticks; string newFilePath = $"{filePath}.{uniqueId}.new"; string tempFilePath = $"{filePath}.{uniqueId}.temp"; File.WriteAllText(newFilePath, JsonConvert.SerializeObject(toSave, options.Indent ? Formatting.Indented : Formatting.None, options.GetSerializationSettings())); // If the file does not exist yet, create it. if (!File.Exists(filePath)) { File.Move(newFilePath, filePath); if (options.SaveBackupFile) { File.Copy(filePath, $"{filePath}.bak", true); } return; } if (options.SaveBackupFile) { File.Copy(filePath, $"{filePath}.bak", true); } // Delete the file and rename the temp file to that of the target file. File.Move(filePath, tempFilePath); File.Move(newFilePath, filePath); try { File.Delete(tempFilePath); } catch (IOException) { // Marking the file for deletion in the future. File.Move(tempFilePath, $"{ filePath}.{ uniqueId}.del"); } }
static FileStorageOption() { Default = new FileStorageOption(); }