I have following code to save data:
File.Copy("data.txt", "data_backup.txt", true);
File.WriteAllText("data.txt", JsonConvert.SerializeObject(new
{
bool1,
string1,
decimal1,
decimal2,
int1,
datetime,
object1,
object2
}, new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = new List<JsonConverter>() { new DontIntendArray() } }));
which my program executes every 15 seconds. Size of data.txt is about 9 MB.
From time to time when my computer crashes then after restart I find out that data.txt is full of NULL characters while its size remains about 9 MB. That is why I added data_backup.txt line but it doesn't help as it saves files full of NULLs as well.
Note that this doesn't happen during every computer but apparently only when it crashes while this code is being executed.
I experienced this behavior while using XMP profile on my RAM which was unstable and caused crash from time to time. It was exactly the same on two different computers with unstable XMR profile. I also experienced it during electricity outage.
I understand that I can't expect crashing computer to flawlessly execute all code and only then crash. However, is there any trick I can use to prevent loss of content of files that are just being written to or saved while or moment before computrer crashes? The whole purpose of regularly saving these variables into file is to prevent loss of data in case of computer crash but apparently this approach doesn't always work.