递归复制所有文件和目录

时间:2013-03-22 18:19:34

标签: c# recursion

我想找到扩展名为.zzz的每个文件,然后将该文件的父文件夹(及其所有内容)复制到目标目录。下面的代码有效,但它只复制第一级子目录。

 private void btn_submit_Click(object sender, EventArgs e)
    {
        string srcFolder = txt_src.Text;
        string destFolder = txt_dest.Text;
        foreach (string zzz in Directory.GetFiles(srcFolder, "*.zzz", SearchOption.AllDirectories))
        {
            string modulePath = Directory.GetParent(zzz).FullName;
            string moduleName = Directory.GetParent(zzz).Name;
            Directory.CreateDirectory(destFolder + "\\" + moduleName);
            foreach (string subFolders in Directory.GetDirectories(modulePath, "*", SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(subFolders.Replace(modulePath, destFolder + "\\" + moduleName));
            }
            foreach (string allFiles in Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories))
            {
                File.Copy(allFiles, allFiles.Replace(modulePath, destFolder + "\\" + moduleName), true);
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

你可以递归。我把它放在一起 - 我可能没有完全分析你的变量,但它会给你一个想法。

 private void btn_submit_Click(object sender, EventArgs e)
{
    copy_stuff(txt_src.Text, txt_dest.Text);
}

private void copy_stuff(string srcFolder, string destFolder)
{
    foreach (string zzz in Directory.GetFiles(srcFolder, "*.zzz", SearchOption.AllDirectories))
    {
        string modulePath = Directory.GetParent(zzz).FullName;
        string moduleName = Directory.GetParent(zzz).Name;
        Directory.CreateDirectory(destFolder + "\\" + moduleName);
        foreach (string subFolders in Directory.GetDirectories(modulePath, "*", SearchOption.AllDirectories))
        {
            string dest = subFolders.Replace(modulePath, destFolder + "\\" + moduleName);
            Directory.CreateDirectory(dest);
            copy_stuff(subfolders, dest);
        }
        foreach (string allFiles in Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories))
        {
            File.Copy(allFiles, allFiles.Replace(modulePath, destFolder + "\\" + moduleName), true);
        }
    }
}