23

I want to rename a file in a directory as an atomic transaction. The file will not be changing directories. The path is provided as a UNC Path to an NTFS file system, probably on either Server 03 or 08.

Is File.Move() atomic for these purposes? As in, it either completes successfully or fails such that the original file is still intact?

My gut says yes, but I wanted to make sure.

  • as an aside, SVN makes use of the fact that move is an atomic operation (on most filesystems) extensively for maintaining integrity during updates/commits. – rmeador Apr 21 '09 at 19:44
  • doesn't "atomic" imply that there is more than one operation? how is this specific rename more than one operation? it is NOT a copy+delete. – Lucas Apr 21 '09 at 20:05
  • 1
    @Lucas: atomic means that the operation, regardless of how many steps it is internally, always happens together. It can't be preempted part way through by another thread, etc. This is the original "indivisible" meaning of the word "atomic", which has sense been disproven in the case of actual atoms by modern physics... – rmeador Apr 21 '09 at 20:18
  • 1
    @rmeador: I understand, but this rename is a single-step operation. There is no in-between state, it either has the original name or the new one. Does it make sense to call it atomic? Unless, of course, we consider all single-step operations inherently atomic :) – Lucas Apr 22 '09 at 19:51
  • 5
    Yes, it makes sense to ask if a rename operation is atomic. Just because it is a single operation from the application's view, we can't assume that the file system driver performs the rename in one operation. Maybe it has to update a B-tree of file names, or any number of other things that aren't inherently atomic. It really depends on the file system. – Alex May 06 '11 at 15:16

1 Answers1

23

Yes, in NTFS. From here:

As an aside if you are running under NTFS then file operations are atomic at the file system level. A rename will occur in a single operation as far as any higher code is concerned. The problem you are seeing almost appears to be an issue where the FileInfo object is being shared across applications. It is a MarshalByRef object and therefore can be used in remoting environments. Don't know if this applies to you.

boflynn
  • 3,534
  • 1
  • 27
  • 28
  • Uh, but what if the .net application is running on FAT or accessing something on a fileshare? Where’s `File.Rename()` which would, as part of its API, guarantee that either the rename is performed atomically or it throws an exception indicating that atomicity cannot be achieved? – binki Jan 24 '16 at 06:34
  • 2
    Ah, apparently I want `File.Replace()` which throws an exception on Windows 98 or FAT (or any situation where it can’t guarantee atomicity, or at least that’s what [the docs](https://msdn.microsoft.com/en-us/library/9d9h163f%28v=vs.110%29.aspx) seem to suggest). – binki Jan 24 '16 at 07:45