C# 复制文件并备份现有的+;子目录

C# 复制文件并备份现有的+;子目录,c#,C#,我正在尝试制作一个程序,将特定文件夹中的文件以及主文件夹子文件夹中的文件备份到另一个备份文件夹 这是我试图实现目标的代码的一部分,但是我只备份了主文件夹中的文件,并且子文件夹被完全复制(其中的所有文件) 提前感谢。一个简单的解决方案:在CopyAll方法中,加载search选项。将AllDirectories参数加载到GetFiles方法: foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories)) {

我正在尝试制作一个程序,将特定文件夹中的文件以及主文件夹子文件夹中的文件备份到另一个备份文件夹

这是我试图实现目标的代码的一部分,但是我只备份了主文件夹中的文件,并且子文件夹被完全复制(其中的所有文件)


提前感谢。

一个简单的解决方案:在
CopyAll
方法中,加载
search选项。将AllDirectories
参数加载到
GetFiles
方法:

foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories))
{
    fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
你也可以试着用这种方法 容易得多

//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);
您可以与
SearchOption.AllDirectories
一起使用,也可以从子文件夹中提取文件:

Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)

该解决方案可以工作,但是文件被复制到根目录/没有创建子目录/。我可能做错了什么,因为我是新来的。
//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);
Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)