到一个目录中的全部内容复制在C#中的最佳方法全部内容、方法、目录中

2023-09-02 10:15:08 作者:孤冷

欲一个目录中的全部内容从一个位置复制到另一在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);