views:

111

answers:

3

Is there anyway another process monitoring for files created using XMLDocument.Save() could encounter a partial file? Does it make any difference if Save() is overwriting an existing file?

+4  A: 

If you save like this you shouldn't have any problems.

using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
    xmlDoc.Save(file);
}
ChaosPandion
Beat me to the punch by about 3 seconds. Have an upvote :)
Jesse C. Slicer
+2  A: 

I don't think that there is any guarantee of atomicity. You should not depend on it.

John Saunders
What about saving a temp file instead and then renaming it? Could the rename be done atomically, or does the file system just not work this way?
JC
I would think that a rename would do the job. It depends on how much of a "guarantee" you want. If you want a "real" guarantee, then you want to look in the documentation for a statement that the operation is atomic. You might need to look at the .NET code using Reflector to see what Win32 calls it makes, then research whether those calls are atomic. Otherwise, it's probably good enough to realize that a rename from one directory to another on the same volume really just creates a new directory entry and deletes the old. Not complicated, and likely atomic.
John Saunders
A: 

Writing files is, in general, not atomic. Check out Process Monitor to get an idea what the OS exposes.

XmlDocument.Save(string) uses FileShare.Read. ChaosPandion's solution specifies FileShare.None. Check out System.IO.FileShare on MSDN for the difference.

Justin R