How to Copy the entire contents of a directory in C#?


While copying the entire contents of directory, it is more important that we have copy its sub directories and the related files.

Example

Let us consider demo source directory having sub directories and files like below.

 

Below is the demo target directory which is empty initially.

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);
         }
      }
   }
}

Output

The output of the above code is

Updated on: 08-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements