Alex Rivera | Logout

What is the best way to copy a folder and all subfolders and files using c#

Asked 2010-04-30T04:29:52.600
9

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.

c#
Edit
Report

2 Answers

12

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));
}
answered 2010-04-30T04:52:52.467
-1

Why dont you use something like Robocopy?

It has a mirroring option where the directory structure of source is copied as-is inot te destination. There are various command line options. Might save you the effort to replicate the features in your code.

answered 2010-04-30T04:49:45.050

Your Answer