While copying the entire directory, it is more important that we copy its subdirectories and related files.
Let us consider the following example source directory, which contains subdirectories and files.
The following is a sample target directory, initially empty.
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); } } } }
The output result of the above code is
The above is the detailed content of How to copy the entire contents of a directory in C#?. For more information, please follow other related articles on the PHP Chinese website!