How to create a recursive function to copy all files and folders

I am trying to create a function that will recursively copy the source folder and all files and folders inside it to another location.

At the moment, I have to define each folder in the main folder, which makes the code bloated and redundant.

What is a more efficient way to do this?

+6
source share
4 answers

take a look at my question:

directory copying performance I used parallel foreach and it is very fast

private static void CopyAll(string SourcePath, string DestinationPath) { string[] directories = System.IO.Directory.GetDirectories(SourcePath, "*.*", SearchOption.AllDirectories); Parallel.ForEach(directories, dirPath => { Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); }); string[] files = System.IO.Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories); Parallel.ForEach(files, newPath => { File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath)); }); } 
+9
source

Source: C # - copy files and folders recursively from the source folder to the c-sharp folder

 public static void CopyFolder(string sourceFolder, string destFolder) { if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder); string[] files = Directory.GetFiles(sourceFolder); foreach (string file in files) { string name = Path.GetFileName(file); string dest = Path.Combine(destFolder, name); File.Copy(file, dest); } string[] folders = Directory.GetDirectories(sourceFolder); foreach (string folder in folders) { string name = Path.GetFileName(folder); string dest = Path.Combine(destFolder, name); CopyFolder(folder, dest); } } 
+4
source

Do it like that

  void Copy(string sourceDir, string targetDir) { Directory.CreateDirectory(targetDir); foreach (var file in Directory.GetFiles(sourceDir)) File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file))); foreach (var directory in Directory.GetDirectories(sourceDir)) Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory))); } 
+1
source

Using GetDirectories / GetFiles is somewhat outdated in my eyes, instead I would use Directory.EnumerateFileSystemEntries(source); because it is faster.

0
source

Source: https://habr.com/ru/post/914571/


All Articles