We have a problem in our Windows 8.1 application (WinRT) that sometimes our saved file gets corrupt. The files have a correct file size, but the file only contains NUL-characters. The file should contain a serialized object as XML.
In an attempt to find the issue we do not overwrite the file, we do the following:
- Serialize the current object to a temp file.
- Check the content of the temp file
- Copy the current file (to .timestamp.xml.bak)
- Move/replace the temp file to the current file
Most of the time this all works fine, but sometimes the .timestamp.xml.bak-file and the content file get corrupt. Besides that, also the log file gets corrupt (also only NUL-characters). The whole file consists of NUL-characters. When I look at the trail of bak-files and the main file, I see that the main file is increased in size. That should be correct because a new XML-element is added. But it doesn’t contain XML.
I do not have a clue how and why this happens. It occurs in about 5% of files which should be edited and each corrupt file happens after 5-20 save attempts. It also happens on several tablets.
Here is a snippet of the code which creates the corrupt files:
StorageFile file = await lDataFld.CreateFileAsync(filename + ".tmp", CreationCollisionOption.OpenIfExists);
StorageFile oldFile = await dataFld.GetFileAsync(filename + ".xml");
if (oldFile != null)
{
await oldFile.CopyAsync(dataFld, string.Format("{0}.{1}.xml.bak", filename, DateTime.Now.ToString("yyyyMMddHHmmssfffffff")), NameCollisionOption.ReplaceExisting);
}
await file.MoveAndReplaceAsync(await dataFld.GetFileAsync(filename + ".xml"));
Logger.Log(string.Format("Saved {0}.", filename));
Can someone tell me how we end up with files containing only NUL-characters and how/why this happens? And even better how it can be fixed.
A small adition: we cannot reproduce this issue in any way, it only occurs on our production environment.