C# – Copy directory with all files and folders

cnet

I'm trying to copy one directory to another path.
I found this method, but it does not copy the directory, only the sub-directories and files inside it:

string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");

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);
}

How I can get the "Program" folder in output with all files and sub-folders?

Best Answer

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);
}