Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a Move method, but not a Copy method in Directory class from System.IO?

Tags:

c#

.net

As the title says, there's a Directory.Move but no Directory.Copy method in Directory class from System.IO. Is there a reason for that?

Update:

To me, the copy and move actions are pretty much identical, the only difference being that the move action does a copy and then deletes the destination. And the error handling is as complex for move as it is for copy. So if one is implemented, why isn't the other?

Update 2:

This is a quote from a comment from mmclean:

Directory.Move however does not move, it renames. Thus the "destination" path is a full path to point to the directory, rather than a location to "move into", and moving to a different drive is impossible.

So I understand that move actually does a rename operation (only changes and entry in the File Allocation Table). But both move and copy commands have the same problem with merging items existing in the destination (overwrite/keep both). So the only added complexity for the copy operation is that it has to physically copy files around. But that still doesn't explain the decision to not implement it. Even more so, when the copy command is implemented in VB.NET and there's a pretty simple implementation for a copy operation on MSDN here.

like image 774
david.s Avatar asked Feb 15 '23 10:02

david.s


1 Answers

The pragmatic answer is that there is no Windows API call to copy a directory, whereas there is a Windows API call to move (aka rename) a directory (MoveFile()).

Directory.Move() calls MoveFile() as part of its implementation. But there is nothing it can call for copying.

They seem to have kept the interface broadly similar to that provided by the Windows API.

Furthermore, the error handling for a failed directory copy is pretty nasty. Would it have to roll back any changes? How to handle a failed copy is going to be so context-dependent that it's pretty hard to have a general-purpose approach. That's probably why there's no Windows API call to copy a directory too.

Another thing that can cause added complexity is different files being locked during the copy, and files being added and removed from the directory while the copy is taking place.

(Although as noted in another answer here, there's a Visual Basic method to copy a directory, which must address some of these issues.)

like image 81
Matthew Watson Avatar answered Feb 18 '23 14:02

Matthew Watson