复制文件夹及文件
/// <summary> /// 复制文件夹及文件 /// </summary> /// <param name="sourceFolder">源文件夹路径</param> /// <param name="destFolder">目标文件夹路径</param> /// <returns></returns> public int CopyFolder2(string sourceFolder, string destFolder) { try { string folderName = System.IO.Path.GetFileName(sourceFolder); string destfolderdir = System.IO.Path.Combine(destFolder, folderName); string[] filenames = System.IO.Directory.GetFileSystemEntries(sourceFolder); string Basedestfolderdir = destfolderdir; DirectoryInfo TheFolder = new DirectoryInfo(destfolderdir); foreach (string file in filenames)// 遍历所有的文件和目录 { string srcfileName = System.IO.Path.Combine(destfolderdir, System.IO.Path.GetFileName(file)); //判断如果不是文件则进入复制文件夹,如果是文件则进行复制 // true if path refers to an existing directory; false if the directory does // not exist or an error occurs when trying to determine if the specified file // exists. if (!Directory.Exists(file)) { if (!System.IO.Directory.Exists(destfolderdir)) { System.IO.Directory.CreateDirectory(destfolderdir); } log.ErrorFormat("目标文件路径确认无误:{0}", destfolderdir); //判断文件是否已经存在 //如果不存在,则复制文件到目标路径 //如果调用者具有所需的权限,且路径包含名称,则为true if (!File.Exists(srcfileName)) { System.IO.File.Copy(file, srcfileName); } } else { //判断是文件夹,进入继续遍历 CopyFolder2(file, Basedestfolderdir); } } return 1; } catch (Exception ex) { log.ErrorFormat("复制文件夹失败:{0}", ex); return 0; } }