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
class
If you like Konrad's popular answer, but you want the source
itself to be a folder under target
, rather than putting it's children under the target
folder, here's the code for that. It returns the newly created DirectoryInfo
, which is handy:
public static DirectoryInfo CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
var newDirectoryInfo = target.CreateSubdirectory(source.Name);
foreach (var fileInfo in source.GetFiles())
fileInfo.CopyTo(Path.Combine(newDirectoryInfo.FullName, fileInfo.Name));
foreach (var childDirectoryInfo in source.GetDirectories())
CopyFilesRecursively(childDirectoryInfo, newDirectoryInfo);
return newDirectoryInfo;
}