c# 封装的文件夹操作类之复制文件夹
一.复制文件夹原理:
1.递归遍历文件夹
2.复制文件
二.FolderHelper.cs
1 /// <summary> 2 /// 文件夹操作类 3 /// </summary> 4 public static class FolderHelper 5 { 6 /// <summary> 7 /// 复制文件夹 8 /// </summary> 9 /// <param name="sourceFolderName">源文件夹目录</param> 10 /// <param name="destFolderName">目标文件夹目录</param> 11 public static void Copy(string sourceFolderName, string destFolderName) 12 { 13 Copy(sourceFolderName, destFolderName, false); 14 } 15 16 /// <summary> 17 /// 复制文件夹 18 /// </summary> 19 /// <param name="sourceFolderName">源文件夹目录</param> 20 /// <param name="destFolderName">目标文件夹目录</param> 21 /// <param name="overwrite">允许覆盖文件</param> 22 public static void Copy(string sourceFolderName, string destFolderName, bool overwrite) 23 { 24 var sourceFilesPath = Directory.GetFileSystemEntries(sourceFolderName); 25 26 for (int i = 0; i < sourceFilesPath.Length; i++) 27 { 28 var sourceFilePath = sourceFilesPath[i]; 29 var directoryName = Path.GetDirectoryName(sourceFilePath); 30 var forlders = directoryName.Split(‘\\‘); 31 var lastDirectory = forlders[forlders.Length - 1]; 32 var dest = Path.Combine(destFolderName, lastDirectory); 33 34 if (File.Exists(sourceFilePath)) 35 { 36 var sourceFileName = Path.GetFileName(sourceFilePath); 37 if (!Directory.Exists(dest)) 38 { 39 Directory.CreateDirectory(dest); 40 } 41 File.Copy(sourceFilePath, Path.Combine(dest, sourceFileName), overwrite); 42 } 43 else 44 { 45 Copy(sourceFilePath, dest, overwrite); 46 } 47 } 48 } 49 }
时间: 2024-10-21 15:50:09