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

查看:109
本文介绍了复制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.

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

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?

推荐答案

容易得多

//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", 
    SearchOption.AllDirectories))
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

//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, DestinationPath), true);

这篇关于复制C#中目录的全部内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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