Ejemplo n.º 1
0
        /// <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;
            }

            var filePath     = Path.Combine(this.FolderPath, fileName);
            var uniqueId     = DateTime.UtcNow.Ticks;
            var newFilePath  = $"{filePath}.{uniqueId}.new";
            var 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");
            }
        }
Ejemplo n.º 2
0
 static FileStorageOption()
 {
     Default = new FileStorageOption();
 }