复制包含所有文件和文件夹的目录

时间:2014-11-07 01:14:14

标签: c# .net

我试图将一个目录复制到另一个路径 我找到了这个方法,但它不复制目录,只复制其中的子目录和文件:

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

我如何获得"计划"输出中的文件夹包含所有文件和子文件夹?

2 个答案:

答案 0 :(得分:1)

如果在开始复制之前调整输出路径,它应该可以工作:

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

答案 1 :(得分:0)

您可以使用递归函数来执行此操作:

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