在 C# 中复制目录的全部内容 [英] Copy the entire contents of a directory in C#

查看:36
本文介绍了在 C# 中复制目录的全部内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to copy the entire contents of a directory from one location to another in C#.

似乎没有办法使用 System.IO 类在没有大量递归的情况下做到这一点.

There doesn't appear to be a way to do this using System.IO classes without lots of recursion.

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

There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic:

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

这似乎是一个相当丑陋的黑客.有没有更好的办法?

This seems like a rather ugly hack. Is there a better way?

推荐答案

更容易

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# 中复制目录的全部内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆