Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely saving a file in Windows 10 IOT

My team requires a bulletproof way to save a file (less than 100kb) on Windows 10 IOT.

The file cannot be corrupted but it's OK to loose the most recent version if save failed because of power off etc.

Since the File IO has changed significantly (no more File.Replace) we are not sure how to achieve it.

We can see that:

var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
await Windows.Storage.FileIO.WriteTextAsync(file, data);

is reliably unreliable (it repeatedly broke when stopping debugging, or reset the device.) and we are ending up with a corrupted file (full of zeroes) and and a .tmp file next to it. We can recover this .tmp file I'm not confident that we should base our solution on undocumented behaviour.

One way we want to try is:

var tmpfile = await folder.CreateFileAsync(fileName+".tmp",
                               CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(tmpfile, data);

var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

// can this end up with a corrupt or missing file?
await tmpfile.MoveAndReplaceAsync(file); 

In summary, is there a safe way to save some text to a file that will never corrupt the file?

like image 289
tymtam Avatar asked Nov 07 '22 20:11

tymtam


1 Answers

Not sure if there's a best practice for this, but if needed to come up with something myself:

I would do something like calculating a checksum and save that along with the file.

When saving the next time, don't overwrite it but save it next to the previous one (which should be "known good"), and delete the previous one only after verifying that the new save completed successfully (together with the checksum)

Also I would assume that a rename operation should not corrupt the file, but I haven't researched that

like image 106
hansmbakker Avatar answered Nov 14 '22 22:11

hansmbakker