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

CsharpServer Side ProgrammingProgramming

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


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);
      public static void CopyAll(DirectoryInfo source, DirectoryInfo target) {
         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 =
            CopyAll(diSourceSubDir, nextTargetSubDir);


The output of the above code is

Published on 08-Aug-2020 14:58:30