patterncsharpCritical
Copy the entire contents of a directory in C#
Viewed 0 times
directoryentirecontentsthecopy
Problem
I want to copy the entire contents of a directory from one location to another in C#.
There doesn't appear to be a way to do this using
There is a method in VB that we can use if we add a reference to
This seems like a rather ugly hack. Is there a better way?
There doesn't appear to be a way to do this using
System.IO classes without lots of recursion.There is a method in VB that we can use if we add a reference to
Microsoft.VisualBasic:new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );This seems like a rather ugly hack. Is there a better way?
Solution
Much easier
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}Code Snippets
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}Context
Stack Overflow Q#58744, score: 670
Revisions (0)
No revisions yet.