Copying Files Recursively
Asked Answered
D

3

5

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)

Dockage answered 15/8, 2011 at 12:25 Comment(1)
see this Answer #628004Bidding
B
-2

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);
}
Bidding answered 15/8, 2011 at 12:32 Comment(1)
source.GetFiles() won't recursively get files in subdirectories, but only in the "source" directory.Bayard
A
26

MSDN has a complete sample: How to: copy directories

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(string sourceDirName, string destDirName, 
                                      bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}
Ablution answered 15/8, 2011 at 12:34 Comment(0)
A
0

A non-recursive replacement for this answer would be:

private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
    if (!Directory.Exists(sourceBasePath))
        throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");

    var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
    directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
    while (directoriesToProcess.Any())
    {
        (string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();

        if (!Directory.Exists(destinationPath))
            Directory.CreateDirectory(destinationPath);

        var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
        foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
            sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);

        if (!recursive)
            continue;

        foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
            directoriesToProcess.Enqueue((
                sourcePath: sourceSubDirectoryInfo.FullName,
                destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
    }
}
Atreus answered 29/10, 2018 at 20:59 Comment(0)
B
-2

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);
}
Bidding answered 15/8, 2011 at 12:32 Comment(1)
source.GetFiles() won't recursively get files in subdirectories, but only in the "source" directory.Bayard

© 2022 - 2024 — McMap. All rights reserved.