Save settings to "filename.json.temp" file and rename it to actual file name for decrease probability of save corruption happen when pc shutdown

This commit is contained in:
Jaex 2015-12-01 11:07:49 +02:00
parent 551a47bac1
commit 8447e68548

View file

@ -57,17 +57,26 @@ public static bool Save(object obj, string filePath, SerializationType type, boo
{
lock (obj)
{
using (MemoryStream ms = new MemoryStream())
{
Save(obj, ms, type);
string tempFilePath = filePath + ".temp";
if (createBackup && File.Exists(filePath))
using (FileStream fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
Save(obj, fs, type);
}
if (File.Exists(filePath))
{
if (createBackup)
{
File.Copy(filePath, filePath + ".bak", true);
}
isSuccess = ms.WriteToFile(filePath);
File.Delete(filePath);
}
File.Move(tempFilePath, filePath);
isSuccess = true;
}
}
}