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
Release: 2023-09-12 21:17:03
forward
1037 people have browsed it

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);
         }
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template