Search code examples
c#shutdownxelement

XML file data is lost when sudden shutdown is occurred


I have an application that stores data in XML file every 500 ms using XElement object's .Save("path") method. The problem is : when a sudden shutdown is occurred the content of the file is deleted so on the next run of the application the file can not be used.

How to prevent that / make sure the data will not be lost? P.S: I'm using .NET 2010 C# under windows 7

I've made an experiment: instead of writing to the same data.xml file I've created (by copying from the original file) a new file each time and when the power was off while copying from data.xml file it would corrupt all previously created files?!?!?


Solution

  • Let's assume your file is data.xml. Instead of writing to data.xml all the time, write to a temporary file data.xml.tmp, and when finished, rename it to data.xml. But renaming will not work if you already have a data.xml file, so you will need to delete it first and then rename the temporary file.

    That way, data.xml will contain the last safe data. If you have a sudden shutdown, the incomplete file will be the temporary data.xml.tmp. If your program tries to read the file later on and there is no data.xml file, that means the shutdown happened between the delete and rename operations, so you will have to read the temporary file instead. We know it is safe because otherwise there would be a data.xml file.