Search code examples
.netsystem.io.filesystem.io.directory

.NET Directory.Move() vs File.Move()


We have an application that stores files in a temporary location until the user decides to finalize their transaction. The temp directory is unique for each transaction. Once they do finalize, the files are moved from the temp location to a final location, which is also unique for each transaction. This is all working without any issues.

I'm rather surprised, but when searching Google and SO, we were unable to find any topics on which is generally considered a best practice:

  1. Call System.IO.Directory.Move(src, des) to simply move the whole directory at once, or
  2. Call System.IO.File.Move(src, des) to move the files one at a time.

As these decisions typically rely on a number of factors, I should note the following conditions:

  1. The source and destination directories will always be on the same machine, but the application making the calls will be on a different machine on the same network. I believe the application server and file server are separate VM's on the same physical machine, but I am not positive.
  2. The number of files could range from 1 to 10, or more. I do not monitor the production system myself, so I am unsure of the average file count, or how spread the count is.

Solution

  • I think the biggest issue is not speed but rather: what happens on a move error?

    I'm going to use the information in LukeH's answer rather than repeating it here.

    The behaviour of MoveFile for a directory move should be appropriate for if it fails to move a single file. If you use a per file move, then you have to handle the error conditions yourself in an appropriate manner. This requires some careful thought.

    Note that the documentation of MoveFile specifies that:

    The one caveat is that the MoveFile function will fail on directory moves when the destination is on a different volume.

    That might or might not be an issue for you and reason to use a per-file Move. The Directory.Move documentation explicitly mentions this (and the reference source for Directory.Move explicitly checks for source and destination having the same root).