DotNet
DotNet

Reputation: 59

Copy directory with all files and folders

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?

Upvotes: 3

Views: 7130

Answers (2)

Damian Lascarez
Damian Lascarez

Reputation: 46

You can use a recursive function to do it:

private void button1_Click(object sender, EventArgs e)
    {
        this.CopyAll(new DirectoryInfo(@"D:\Original"), new DirectoryInfo(@"D:\Copy"));
    }
    private void CopyAll(DirectoryInfo oOriginal, DirectoryInfo oFinal)
    {
        foreach (DirectoryInfo oFolder in oOriginal.GetDirectories())
            this.CopyAll(oFolder, oFinal.CreateSubdirectory(oFolder.Name));

        foreach (FileInfo oFile in oOriginal.GetFiles())
            oFile.CopyTo(oFinal.FullName + @"\" + oFile.Name, true);
    }

Upvotes: 1

Peter Duniho
Peter Duniho

Reputation: 70701

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

Upvotes: 1

Related Questions