Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reliability around the resource based file system #229

Open
einari opened this issue May 29, 2019 · 0 comments
Open

Add reliability around the resource based file system #229

einari opened this issue May 29, 2019 · 0 comments

Comments

@einari
Copy link

einari commented May 29, 2019

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

@einari einari closed this as completed Oct 16, 2019
@einari einari reopened this Oct 21, 2019
@einari einari closed this as completed Oct 31, 2019
@einari einari reopened this Nov 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant