Reputation: 4741
I am developing a tool in c#, at one instance I start writing into a xml file continuously using my tool,when i suddenly restart my machine the particular xml file gets corrupted, what is the reason an how to avoid it?
xmldocument x= new xmldocument();
x.open();
// change a value of the node every time
x.save();
x=null
this is my code
Upvotes: 0
Views: 127
Reputation: 1842
The reason for your file getting corrupted is that due to a crash, you never closed it. I remember solving an issue like that once, with a file overlapping flag. But that was in C++ using method CreateFile.
Upvotes: 0
Reputation: 354824
Don't use XML.
XML has a syntax which doesn't lend itself well to writing continuously to the same file, as you always need a final end tag which you can't write unless the file is complete (which it never is with log files, for example).
That means you will always get an invalid XML file when you cancel the writing prematurely (by killing the process or restarting the computer, etc.).
We had a similar situation a while ago and settled on YAML as a nice format which allows for simply appending to the file.
Upvotes: 2
Reputation: 5804
Check that your file is properly closed before the application shuts down.
Also, as someone has pointed out, an XML file must be properly ended with closing tags.
Additional details would also be useful, such as the code that you use to open, write and close the file.
Upvotes: 0
Reputation: 1503419
Use the "safe replace pattern". For example, to replace foo.txt
At any point, you have at least one complete, valid file.
(That helps if you want to write a new file periodically; for appending, I'd go with the answers suggesting that XML isn't the best way forward for you.)
Upvotes: 2