开发者

Is XMLDocument.Save an atomic operation?

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 ove开发者_如何学运维rwriting an existing file?


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);
}


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


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.


This answer https://stackoverflow.com/a/487198/1429390 provides AFAIK some kind of atomicity in an easy-to-use fashion. The principle is to write in a temporary file and provide caller an opportunity to rename the file (and whatever else you want) at close time. That way, whatever may happen while creating and filling the file cannot clobber a possibly existing file.

Update: except it doesn't because System.IO.File.Move() refuses to overwrite. See https://stackoverflow.com/a/10305475/1429390 for a workaround.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜