Is XMLDocument.Save an atomic operation?

后端 未结 4 921
傲寒
傲寒 2021-01-12 08:58

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

相关标签:
4条回答
  • 2021-01-12 09:18

    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.

    0 讨论(0)
  • 2021-01-12 09:26

    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);
    }
    
    0 讨论(0)
  • 2021-01-12 09:28

    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 讨论(0)
  • 2021-01-12 09:36

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

    0 讨论(0)
提交回复
热议问题