Answered by:

Directory.Copy

Question

There is a static File.Copy method. Why is there not a static Directory.Copy method? Why does attempting to copy a directory using the File.Copy method result in an error saying access is denied while using Directory.Move on the same directory works fine?

All replies

You right, there is no Directory.Copy() method, only Move(). Actually a little strange. Only one explanation (but not perfect) comes to my mind - error processing are much harder, in case of single file you will be able to rollback in cases of failure, but what if you copy half of directory and other half can't be copied - how to deal with files that already copied? To avoid such hard questions - Copy() method omitted. You app can implement all this stuff by manual files/folders enumeration and File.Copy()/Directory.Create() each file/folder. In case of error - you need to do something, clean up for example.

Directory.Move isn't really a move method, it's a rename method. You'll notice there are restrictions like it can only be 'moved' onto the same drive which means there's not actualy data copying just a bit of fixing up of file system links.

The reason there is no proper Directory.Move which can move to anywhere, or Directory.Copy which does a copy, it because it's not possible to know how you want it to behave. Sure, with most directories it will be fine. But if you've got a reparse point that points internally to the directory then you would hit an infinite loop. OK, so ignore reparse points. But now you're not faithfully copying the directory structure. And how do you want to handle sparse files? Or any other anomalies the directory structure could throw at you? The problem is it's very difficult to model a 'correct' behaviour as there isn't just one, so it is left up to you to model your own 'correct' behaviour.