如何在 C# 中复制目录的全部内容?
在复制目录的全部内容时,更重要的是,我们复制其子目录和相关文件。
示例
我们考虑具有如下所示的子目录和文件演示源目录。
以下是最初为空的演示目标目录。
using System; using System.IO; namespace DemoApplication { class Program { public static void Main() { string sourceDirectory = @"d:\DemoSourceDirectory"; string targetDirectory = @"d:\DemoTargetDirectory"; DirectoryInfo sourceDircetory = new DirectoryInfo(sourceDirectory); DirectoryInfo targetDircetory = new DirectoryInfo(targetDirectory); CopyAll(sourceDircetory, targetDircetory); Console.ReadLine(); } public static void CopyAll(DirectoryInfo source, DirectoryInfo target) { Directory.CreateDirectory(target.FullName); foreach (FileInfo fi in source.GetFiles()) { Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); fi.CopyTo(Path.Combine(target.FullName, fi.Name), true); } foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } } } }
输出
上述代码的输出为
广告