Reputation: 59
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
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
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