karthik
karthik

Reputation: 4741

File Handling Issue

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

Answers (4)

Vladimir Kocjancic
Vladimir Kocjancic

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

Joey
Joey

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

Dario Solera
Dario Solera

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

Jon Skeet
Jon Skeet

Reputation: 1503419

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

Upvotes: 2

Related Questions