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();
}
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 aFile.Move()
if its an entirely new file.The following code is an example of how this can be done.
┆Issue is synchronized with this Asana task