dolittle-obsolete / DotNET.Fundamentals

Reusable, fundamental abstractions and building blocks
http://www.dolittle.io
MIT License
4 stars 8 forks source link

Add reliability around the resource based file system #229

Open einari opened 5 years ago

einari commented 5 years ago

There are situations where a program might crash while a file stream is being written to midstream. That means you'll end up with a corrupt file. One way to get around this is to think transactionally about it; do not replace the actual file unless the writing was ok. In .NET this means we can do a File.Replace() if the file exists already - or a File.Move()if its an entirely new file.

The following code is an example of how this can be done.

 var target = "test.txt";
 var tmp = $"{target}_tmp";
 var backup = $"{target}_backup";

var file = File.Open($"{target}_tmp", FileMode.OpenOrCreate);
 try
 {
 var textAsBytes = Encoding.UTF8.GetBytes($"Hello world : {DateTimeOffset.UtcNow}");
 file.Write(textAsBytes, 0, textAsBytes.Length);
 throw new Exception();

if (!File.Exists(target))
 {
 Console.WriteLine("Move");
 File.Move(tmp, target);
 }
 else
 {
 Console.WriteLine("Replace");
 File.Replace(tmp, target, backup);
 }
 }
 catch
 {
 Console.WriteLine("Problems");
 file.Close();
 File.Delete(tmp);

}
 finally
 {
 file.Close();

}

┆Issue is synchronized with this Asana task