English 中文(简体)
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

问题回答

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

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.

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.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签