c# - 在 C# 中复制目录的全部内容

标签 c# .net directory copy

我想在 C# 中将目录的全部内容从一个位置复制到另一个位置。

似乎没有办法在没有大量递归的情况下使用 System.IO 类来执行此操作。

如果我们添加对 Microsoft.VisualBasic 的引用,我们可以使用 VB 中的一种方法:

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

这似乎是一个相当丑陋的 hack。有没有更好的办法?

最佳答案

简单多了

private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
    }

    //Copy all the files & Replaces any files with the same name
    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
    {
        File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
    }
}

关于c# - 在 C# 中复制目录的全部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58744/

相关文章:

c# - 如何在 Process.StandardOutput 中禁用输出缓冲

c# - 按递增顺序将列表拆分为多个列表

c# - 具有 3 位数字或 4 个字母数字字符的正则表达式 C#

Sharepoint 2010 : Can't create a folder in a custom list

date - 在 powershell 中创建以当前日期为名称的文件夹

c# - 用 IoC (CaSTLe Windsor) 替换以下代码

c# - 如何使用 linqto SQL 启用事务处理我的代码?

.net - Teamcity 未满足要求 : MSBuildTools12. 0_x86_Path 存在

c# - 为什么我的区域特定 Web API 可以从所有其他区域访问?

perl - 如何从特定目录中获取具有特定扩展名的所有文件的列表?