How to create a recursive function to copy all files and folders
16,404
Solution 1
Source: C# - Copy files and folders recursively from source to destination folder in c-sharp
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);
}
}
Solution 2
Do it this way
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)));
}
Comments
-
G_Man almost 2 years
I am trying to create a function that will recursively copy a source folder and all files and folders inside of it to a different location.
At the moment, I have to define each folder within the main folder, which is making the code bloated and redundant.
What's a more efficient way of doing this?