Reputation: 53
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:
As these decisions typically rely on a number of factors, I should note the following conditions:
Upvotes: 3
Views: 1959
Reputation: 5477
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).
Upvotes: 1
Reputation: 269278
I'm not sure if there is any fixed "best practice" other than that you should use the most appropriate tool for the job.
Since what you're doing is moving the entire directory from its temporary location/status to a permanent location/status I would suggest using Directory.Move
. This means that your code will more obviously reflect your logical intent.
And if you're more concerned about the technical difference between the two methods...
In the Microsoft version of .NET, both Directory.Move
and File.Move
eventually call out to the Win32 MoveFile
or MoveFileEx
functions. You can confirm this by looking at the Reference Source:
Directory.Move
--> Directory.InternalMove
--> Win32Native.MoveFile
File.Move
--> File.InternalMove
--> Win32Native.MoveFile
With this in mind, it seems likely that calling out to MoveFile
once (via Directory.Move
) would generally be preferable to calling it many times for each transaction (via File.Move
).
Upvotes: 4