This code written to copy files and folders recursively from one drive to another drive using C#, It could be physical storage, logical storage or network location.
private static void Copy(string sourcePath, string targetPath)
{
foreach (string f in Directory.GetFiles(sourcePath))
File.Copy(f, targetPath + "\\" + Path.GetFileName(f), true);
foreach (string d in Directory.GetDirectories(sourcePath))
{
var dirName = Path.GetFileName(d);
Directory.CreateDirectory(targetPath + "\\" + dirName);
Copy(sourcePath + "\\" + dirName, targetPath + "\\" + dirName);
}
}
All the files are copying in synchronization, If wish to perform same operation in Asynchronization and complete the operation quickly. Rewriting same code using Parallel ForEach
private static void Copy(string sourcePath, string targetPath)
{
Parallel.ForEach(Directory.GetFiles(sourcePath), f =>
{
File.Copy(f, targetPath + "\\" + Path.GetFileName(f), true);
});
Parallel.ForEach(Directory.GetDirectories(sourcePath), d =>
{
var dirName = Path.GetFileName(d);
Directory.CreateDirectory(targetPath + "\\" + dirName);
Copy(sourcePath + "\\" + dirName, targetPath + "\\" + dirName);
});
}
All the files and folder are copying in async. It takes less time than synchronization process.
Please feel free to write any queries or comments.
private static void Copy(string sourcePath, string targetPath)
{
foreach (string f in Directory.GetFiles(sourcePath))
File.Copy(f, targetPath + "\\" + Path.GetFileName(f), true);
foreach (string d in Directory.GetDirectories(sourcePath))
{
var dirName = Path.GetFileName(d);
Directory.CreateDirectory(targetPath + "\\" + dirName);
Copy(sourcePath + "\\" + dirName, targetPath + "\\" + dirName);
}
}
All the files are copying in synchronization, If wish to perform same operation in Asynchronization and complete the operation quickly. Rewriting same code using Parallel ForEach
private static void Copy(string sourcePath, string targetPath)
{
Parallel.ForEach(Directory.GetFiles(sourcePath), f =>
{
File.Copy(f, targetPath + "\\" + Path.GetFileName(f), true);
});
Parallel.ForEach(Directory.GetDirectories(sourcePath), d =>
{
var dirName = Path.GetFileName(d);
Directory.CreateDirectory(targetPath + "\\" + dirName);
Copy(sourcePath + "\\" + dirName, targetPath + "\\" + dirName);
});
}
All the files and folder are copying in async. It takes less time than synchronization process.
Please feel free to write any queries or comments.
Comments
Post a Comment