在复制整个目录的同时,更重要的是我们要复制其子目录和相关文件。
让我们考虑以下示例源目录,其中包含子目录和文件。
下面是示例目标目录,最初为空。
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); } } } }
以上代码的输出结果为
以上是如何在C#中复制目录的全部内容?的详细内容。更多信息请关注PHP中文网其他相关文章!