Is XMLDocument.Save an atomic operation?

微笑、不失礼 提交于 2019-12-01 04:37:55

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.

Stéphane Gourichon

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!