File Handling Issue

By : karthik

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();;
// change a value of the node every time;

this is my code

By : karthik


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
  • Move foo.txt to foo.old
  • Move 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