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?
This is my code hope this help
You can always use this, taken from Microsofts website.
Try this:
Your xcopy arguments may vary but you get the idea.
Copy folder recursively without recursion to avoid stack overflow.
A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:
If you like Konrad's popular answer, but you want the
source
itself to be a folder undertarget
, rather than putting it's children under thetarget
folder, here's the code for that. It returns the newly createdDirectoryInfo
, which is handy: