Copy the entire contents of a directory in C#
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);
}
}
How to copy and paste a whole directory to a new path recursively?
Here is an example that will recursively clone a directory to another destination directory. In the future, adding in what you have tried to the current question will get you better responses
class Program
{
static void Main(string[] args)
{
CloneDirectory(@"C:\SomeRoot", @"C:\SomeOtherRoot");
}
private static void CloneDirectory(string root, string dest)
{
foreach (var directory in Directory.GetDirectories(root))
{
string dirName = Path.GetFileName(directory);
if (!Directory.Exists(Path.Combine(dest, dirName)))
{
Directory.CreateDirectory(Path.Combine(dest, dirName));
}
CloneDirectory(directory, Path.Combine(dest, dirName));
}
foreach (var file in Directory.GetFiles(root))
{
File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));
}
}
}
Copy directory with all files and folders
If you adjust the output path before you start copying, it should work:
string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");
folderDialog.SelectedPath = Path.Combine(folderDialog.SelectedPath,
Path.GetFileName(sourcedirectory));
foreach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));
}
foreach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);
}
Folder copy in C#
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
From MSDN
Copy all files from a directory without creating subdirectories
I'd it recursively - maybe something like the below pseudo code... not tested..
public void CopyRecursive(string path, string newLocation)
{
foreach(var file in DirectoryInfo.GetFiles(path))
{
File.Copy(file.FullName, newLocation + file.Name);
}
foreach(var dir in DirectoryInfo.GetDirectories(path))
{
CopyRecursive(path + dir.Name, newLocation);
}
}
Copy files from directory recursively smallest first
You could use a simpler method based on the fact that you can get all the files in a directory subtree just asking for them without using recursion.
The missing piece of the problem is the file size. This information could be obtained using the DirectoryInfo
class and the FileInfo
class while the ordering is just a Linq instruction applied to the sequence of files as in the following example.
private static void Copy(string sourceDir, string targetDir)
{
DirectoryInfo di = new DirectoryInfo(sourceDir);
foreach (FileInfo fi in di.GetFiles("*.*", SearchOption.AllDirectories).OrderBy(d => d.Length))
{
string leftOver = fi.DirectoryName.Replace(sourceDir, "");
string destFolder = Path.Combine(targetDir, leftOver);
// Because the files are listed in order by size
// we could copy a file deep down in the subtree before the
// ones at the top of the sourceDir
// Luckily CreateDirectory doesn't throw if the directory exists
// and automatically creates all the intermediate folders required
Directory.CreateDirectory(destFolder);
// Just write the intended copy parameters as a proof of concept
Console.WriteLine($"{fi.Name} with size = {fi.Length} -> Copy from {fi.DirectoryName} to {Path.Combine(destFolder, fi.Name)}");
}
}
In this example I have changed the File.Copy method with a Console.WriteLine just to have a proof of concept without copying anything, but the substitution is trivial.
Notice also that it is better to use EnumerateFiles
instead of GetFiles
as explained in the MSDN documentation
Copy file with specific extension and it's parent folder into a target folder c#
Instead of combining the target path with the source file name, fully replace the source base folder with the destination base folder:
Destination = file.Replace(sourcePath, targetPath)
Then, before copying, make sure the directory exists:
foreach (var file in files)
{
Directory.CreateDirectory(Path.GetDirectoryName(file.Destination));
File.Copy(file.Source, file.Destination);
}
CreateDirectory will return without an error if the directory already exists.
Alternatively, see generic solutions for copying entire directories in this related answer
Related Topics
C# Interfaces. Implicit Implementation Versus Explicit Implementation
How to Create a Custom Authorizeattribute in ASP.NET Core
How to Get a Consistent Byte Representation of Strings in C# Without Manually Specifying an Encoding
C# Compiler Error: "Not All Code Paths Return a Value"
How to Use Linq to Select Object With Minimum or Maximum Property Value
How to Get the Application'S Path in a .Net Console Application
Send Values from One Form to Another Form
Sending Email Through Gmail Smtp Server With C#
How to Pass Data (And References) Between Scenes in Unity
Pass List of Checkboxes into View and Pull Out Ienumerable
Deserialize Json Object into Dynamic Object Using Json.Net
How to Find the Method That Called the Current Method
Increase Upload File Size in ASP.NET Core
Benefits of Using the Conditional : (Ternary) Operator
How to Add a Timeout to Console.Readline()
Extension Method and Dynamic Object
Best Way to Keep Track and Iterate Through Tabs and Windows Using Windowhandles Using Selenium