public static void CopyDirectory(string sourceDirPath,string SaveDirPath) { try { //如果指定的存储路径不存在,则创建该存储路径 if (!Directory.Exists(SaveDirPath)) { //创建 Directory.CreateDirectory(SaveDirPath); } //获取源路径文件的名称 string[] files = Directory.GetFiles(sourceDirPath); //遍历子文件夹的所有文件 foreach(string file in files) { string pFilePath = SaveDirPath + "\\" + Path.GetFileName(file); if (File.Exists(pFilePath)) continue; File.Copy(file, pFilePath, true); } string[] dirs = Directory.GetDirectories(sourceDirPath); //递归,遍历文件夹 foreach (string dir in dirs) { CopyDirectory(dir, SaveDirPath + "\\" + Path.GetFileName(dir)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
第二种
static void CopyFolder(string srcPath, string desPath) { string strFolderName = srcPath.Substring(srcPath.LastIndexOf("\\") + 1, srcPath.Length - srcPath.LastIndexOf("\\") - 1); //获得文件名夹名 if (!Directory.Exists(desPath + "\\" + strFolderName)) Directory.CreateDirectory(desPath + "\\" + strFolderName);//目标文件夹没此文件夹,则创建 string[] strFiles = Directory.GetFiles(srcPath, "", SearchOption.AllDirectories);//获得文件夹所有文件 foreach (string strFilesElement in strFiles) { var strFileName = strFilesElement.Substring(strFilesElement.LastIndexOf("\\") + 1, strFilesElement.Length - strFilesElement.LastIndexOf("\\") - 1); //获得文件名 string tarAddress = desPath + "\\" + strFileName;//目标路径 File.Copy(strFilesElement, tarAddress, true);//复制 } DirectoryInfo dirInfo = new DirectoryInfo(srcPath);//获得其他文件,对每个文件夹做递归操作 DirectoryInfo[] dirPath = dirInfo.GetDirectories(); foreach (var dirPathElement in dirPath) { CopyFolder(srcPath + "\\" + dirPathElement.Name, desPath + "\\" + dirPathElement.Name); } }