C# – the best way to copy a folder and all subfolders and files using c#

c

I need to copy a Folder from one drive to a removable Hard disk.
The Folder which needs to be copied will have many sub folders and files in it.
The input will be Source Path and Target Path.

Like..

Source Path : "C:\SourceFolder"

Target Path : "E:\"

After copying is done, i shud be able to see the folder "SourceFolder" in my E: drive.

Thanks.

Best Answer

I think this is it.

public static void CopyFolder(DirectoryInfo source, DirectoryInfo target) {
    foreach (DirectoryInfo dir in source.GetDirectories())
        CopyFolder(dir, target.CreateSubdirectory(dir.Name));
    foreach (FileInfo file in source.GetFiles())
        file.CopyTo(Path.Combine(target.FullName, file.Name));
}