views:

57

answers:

4

hi all,

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

+2  A: 

Use the "safe replace pattern". For example, to replace foo.txt

  • Write to foo.new
  • Move foo.txt to foo.old
  • Move foo.new to foo.txt
  • Delete foo.old

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.)

Jon Skeet
A: 

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.

Dario Solera
+2  A: 

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.

Joey
That turns out not to be the case - though you need to be slightly creative, yes a single file needs to be well formed however you can cheat and have a wrapper file which has the opening and closing tags and then include in that file by reference the individual elements. This has the advantage that you can then reference the wrapper file and do the nice things to it (like render with XSLT, particularly useful for log files) that makes XML a desirable format in the first place
Murph
You don't even need to be that creative. This is what `System.Xml.ConformanceLevel.Fragment` is for: you can create an `XmlReader` that happily processes XML elements from an input stream that doesn't have a top-level element. You can even use it as the input for an XSLT transform.
Robert Rossney
A: 

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.

Vladimir Kocjancic