File Handling Issue

By : karthik
Source: Stackoverflow.com
Question!

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

By : karthik


Answers

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.



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.



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

By : Jon Skeet


This video can help you solving your question :)
By: admin