递归复制文件

5
我找到了一个用C#进行递归文件复制的代码片段,但是还有些困惑。我需要将一个目录结构复制到另一个位置,类似于以下这样的操作...

源路径:C:\data\servers\mc

目标路径:E:\mc

目前我复制函数的代码如下...

    //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);
        }
    }

问题在于在第二个作用域中,我要么使用Path.GetFileName(file)获取实际文件名而不包含路径,但是失去了“mc”目录结构要么不使用Path.Combine
无论哪种方式,我都需要做一些糟糕的字符串操作。有没有一种好的方法在C#中实现这一点(我对.NET API的缺乏了解导致我过度复杂化了事情)。

4
请查看此回答:https://dev59.com/YHRB5IYBdhLWcg3wbGtB#627518。 - bpgergo
3个回答

26

MSDN有一个完整的示例:如何复制目录

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);
            }
        }
    }
}

0

这个 answer 的非递归替代方案是:

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)));
    }
}

-2

而不是

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

做类似这样的事情

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

2
source.GetFiles() 不会递归获取子目录中的文件,而只会在“source”目录中获取。 - Mikhail Zhuravlev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接