Home >Backend Development >C#.Net Tutorial >How to copy the entire contents of a directory in C#?

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

WBOY
WBOYforward
2023-09-12 21:17:03994browse

While copying the entire directory, it is more important that we copy its subdirectories and related files.

Example

Let us consider the following example source directory, which contains subdirectories and files.

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

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

The following is a sample target directory, initially empty.

How to copy the entire contents of a directory in 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);
         }
      }
   }
}

Output

The output result of the above code is

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

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete