Search code examples
c#.netfile-copying

Copying Files Recursively


I found a small snippet for doing a recursive file copy in C#, but am somewhat stumped. I basically need to copy a directory structure to another location, along the lines of this...

Source: C:\data\servers\mc

Target: E:\mc

The code for my copy function as of right now is...

    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
    }


    // Copy each file into it’s new directory.
    foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(@"Copying {0}\{1}", targetDir, Path.GetFileName(file));
        if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
        {
            int err = Marshal.GetLastWin32Error();
            Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
        }
    }

The issue is that in the second scope, I either:

  1. use Path.GetFileName(file) to get the actual file name without the path but I lose the directory "mc" directory structure or
  2. use "file" without Path.Combine.

Either way I have to do some nasty string work. Is there a good way to do this in C# (my lack of knowledge with the .NET API leads me to over complicating things)


Solution

  • instead of

    foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
    {
    

    do something like this

    foreach (FileInfo fi in source.GetFiles())
    {
         fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
    }