mirror of
https://github.com/ClassiCube/MCGalaxy.git
synced 2025-08-03 19:36:14 -04:00
Use custom StreamWriter to simplify process of more safely writing files to minimise risk of potential data loss
This commit is contained in:
parent
b6cc486990
commit
0adf900232
@ -87,11 +87,10 @@ namespace MCGalaxy.Bots {
|
|||||||
props.Add(data);
|
props.Add(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
string tmpPath = path + ".tmp";
|
|
||||||
try {
|
try {
|
||||||
using (StreamWriter w = new StreamWriter(tmpPath)) { WriteAll(w, props); }
|
using (StreamWriter w = FileIO.CreateGuarded(path)) {
|
||||||
|
WriteAll(w, props);
|
||||||
FileIO.Replace(tmpPath, path);
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
Logger.LogError("Error saving bots to " + path, ex);
|
Logger.LogError("Error saving bots to " + path, ex);
|
||||||
}
|
}
|
||||||
|
@ -57,11 +57,34 @@ namespace MCGalaxy
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Replace(string src, string dst) {
|
/// <summary> Returns a StreamWriter that writes data to a temp file path first,
|
||||||
TryDelete(dst + ".old");
|
/// and only overwrites the real file when .Dispose() is called </summary>
|
||||||
|
/// <remarks> Reduces the chance of data corruption in full disks </remarks>
|
||||||
|
public static StreamWriter CreateGuarded(string path) {
|
||||||
|
return new GuardedWriter(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class GuardedWriter : StreamWriter
|
||||||
|
{
|
||||||
|
readonly string realPath;
|
||||||
|
public GuardedWriter(string path) : base(path + ".tmp") {
|
||||||
|
realPath = path;
|
||||||
|
}
|
||||||
|
|
||||||
File.Move(dst, dst + ".old");
|
protected override void Dispose(bool disposing) {
|
||||||
File.Move(src, dst);
|
base.Dispose(disposing);
|
||||||
|
string src = realPath + ".tmp";
|
||||||
|
string dst = realPath;
|
||||||
|
string old = realPath + ".old";
|
||||||
|
|
||||||
|
FileIO.TryDelete(old);
|
||||||
|
bool didExist = FileIO.TryMove(dst, old);
|
||||||
|
File.Move(src, dst);
|
||||||
|
|
||||||
|
// Only delete old 'good' file if everything worked
|
||||||
|
if (didExist) FileIO.TryDelete(old);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user