COPY目录下的所有子目录和文件到其他目录时间:2021-09-04 12:07:35COPY目录下的所有子目录和文件到其他目录 using System; using System.IO; namespace ConsoleTest { class Program { static void Main(string[] args) { Console.WriteLine("Begin..."); string sourcePath = "E://sourceTest"; string destPath = "E://destTest"; CopyFiles(sourcePath, destPath); Console.WriteLine("OK!"); Console.ReadLine(); } /// <summary> /// COPY目录及文件到目标目录 /// </summary> /// <param name="sourcePath">源目录地址</param> /// <param name="destPath">目标目录地址</param> public static void CopyFiles(string sourcePath, string destPath) { DirectoryInfo rootDir = new DirectoryInfo(sourcePath); //判断根目录是否存在 if (rootDir.Exists) { ExecCopyFiles(rootDir, destPath); } } /// <summary> /// 执行COPY命令 /// </summary> /// <param name="parentDir">父目录</param> /// <param name="destPath">目标目录地址</param> private static void ExecCopyFiles(DirectoryInfo parentDir, string destPath) { destPath = destPath + "//" + parentDir.Name; //创建子目录 Directory.CreateDirectory(destPath); string nowDestPath = "//"; //获取当前目录的直属文件列表 FileInfo[] files = parentDir.GetFiles("*.*", SearchOption.TopDirectoryOnly); //遍历并copy文件到目标文件夹 foreach (FileInfo file in files) { nowDestPath += file.Name; destPath += nowDestPath; file.CopyTo(destPath, false); destPath = destPath.Replace(nowDestPath, ""); } //获取当前目录的一级子目录 DirectoryInfo[] dirs = parentDir.GetDirectories("*.*", SearchOption.TopDirectoryOnly); //遍历并执行COPY操作 foreach (DirectoryInfo dir in dirs) { //递归调用 ExecCopyFiles(dir, destPath); } } } }