【问题标题】:How do I copy a folder and all subfolders and files in .NET? [duplicate]如何在 .NET 中复制文件夹以及所有子文件夹和文件? [复制]
【发布时间】:2010-11-07 04:34:05
【问题描述】:

可能重复:
Best way to copy the entire contents of a directory in C#

我想在 .NET 中将文件夹及其所有子文件夹和文件从一个位置复制到另一个位置。最好的方法是什么?

我在 System.IO.File 类上看到了 Copy 方法,但想知道是否有比爬取目录树更简单、更好或更快的方法。

【问题讨论】:

  • xneuron.wordpress.com/2007/04/12/… 可能对你有帮助;它显示了一个简单的递归方法
  • 我期待什么时候需要对文件系统进行操作,因为我有正当的理由使用递归!

标签: .net file copy directory


【解决方案1】:

嗯,Steve 引用了 VisualBasic.dll 实现,这是我使用过的东西。

private static void CopyDirectory(string sourcePath, string destPath)
{
    if (!Directory.Exists(destPath))
    {
        Directory.CreateDirectory(destPath);
    }

    foreach (string file in Directory.GetFiles(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(file));
        File.Copy(file, dest);
    }

    foreach (string folder in Directory.GetDirectories(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(folder));
        CopyDirectory(folder, dest);
    }
}

【讨论】:

    【解决方案2】:

    Michal Talaga 在他的post 中引用了以下内容:

    • Microsoft 关于为什么在 .NET 中不应该有 Directory.Copy() 操作的解释。
    • 来自 Microsoft.VisualBasic.dll 程序集的 CopyDirectory() 实现。

    但是,基于File.Copy()Directory.CreateDirectory() 的递归实现应该足以满足最基本的需求。

    【讨论】:

    • 这是一个有趣的链接。我不确定微软的论点是否站得住脚。但它确实解释了为什么缺少该功能。
    【解决方案3】:

    如果你没有得到更好的...也许使用Process.Start 来启动robocopy.exe

    【讨论】:

    • Robocopy 在使用 Process.Start 运行时无法正确解析引号,因此您的源/目标路径不得包含空格。如果是这样,您必须使用 8dot3 文件名。 Robocopy 似乎唯一能正确接受引号的情况是来自命令行或 BAT 文件。
    • @Brain2000 如果空格是个问题,你总是可以使用短路径
    猜你喜欢
    • 2011-07-19
    • 2012-04-01
    • 1970-01-01
    • 2017-01-15
    • 2012-07-15
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多