I want to copy the entire contents of a directory from one location to another in C#.
There doesn't appear to be a way to do this using System.IO
classes without lots of recursion.
There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic
:
new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
This seems like a rather ugly hack. Is there a better way?
Here is an extension method for DirectoryInfo a la FileInfo.CopyTo (note the
overwrite
parameter):My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer.
EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.
One variant with only one loop for copying of all folders and files:
Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:
However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.
Sorry for the previous code, it still had bugs :( (fell prey to the fastest gun problem) . Here it is tested and working. The key is the SearchOption.AllDirectories, which eliminates the need for explicit recursion.
tboswell 's replace Proof version (which is resilient to repeating pattern in filepath)