复制文件夹中的所有文件夹与文件到另一个文件夹
1 /// <summary>
2 /// 复制文件夹中的所有文件夹与文件到另一个文件夹
3 /// </summary>
4 /// <param name="sourcePath">源文件夹</param>
5 /// <param name="destPath">目标文件夹</param>
6 public static void CopyFolder(string sourcePath, string destPath)
7 {
8 if (Directory.Exists(sourcePath))
9 {
10 if (!Directory.Exists(destPath))
11 {
12 //目标目录不存在则创建
13 try
14 {
15 Directory.CreateDirectory(destPath);
16 }
17 catch (Exception ex)
18 {
19 throw new Exception("创建目标目录失败:" + ex.Message);
20 }
21 }
22 //获得源文件下所有文件
23 List<string> files = new List<string>(Directory.GetFiles(sourcePath));
24 files.ForEach(c =>
25 {
26 string destFile = System.IO.Path.Combine(new string[] { destPath, System.IO.Path.GetFileName(c) });
27 File.Copy(c, destFile, true);//覆盖模式
28 });
29 //获得源文件下所有目录文件
30 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
31 folders.ForEach(c =>
32 {
33 string destDir = System.IO.Path.Combine(new string[] { destPath, System.IO.Path.GetFileName(c) });
34 //采用递归的方法实现
35 CopyFolder(c, destDir);
36 });
37 }
38 else
39 {
40 throw new DirectoryNotFoundException("源目录不存在!");
41 }
42 }
43
44 public static void CopyDirectory(string srcPath, string destPath)
45 {
46 try
47 {
48 DirectoryInfo dir = new DirectoryInfo(srcPath);
49 FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //获取目录下(不包含子目录)的文件和子目录
50 foreach (FileSystemInfo info in fileinfo)
51 {
52 if (info is DirectoryInfo) //判断是否文件夹
53 {
54 if (!Directory.Exists(destPath + "\" + info.Name))
55 {
56 Directory.CreateDirectory(destPath + "\" + info.Name); //目标目录下不存在此文件夹即创建子文件夹
57 }
58 CopyDirectory(info.FullName, destPath + "\" + info.Name); //递归调用复制子文件夹
59 }
60 else
61 {
62 File.Copy(info.FullName, destPath + "\" + info.Name, true); //不是文件夹即复制文件,true表示可以覆盖同名文件
63 }
64 }
65 }
66 catch (Exception e)
67 {
68 throw;
69 }
70 }
71
72 private void CopyDir(string srcPath, string aimPath)
73 {
74 try
75 {
76 // 检查目标目录是否以目录分割字符结束如果不是则添加
77 if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
78 {
79 aimPath += System.IO.Path.DirectorySeparatorChar;
80 }
81 // 判断目标目录是否存在如果不存在则新建
82 if (!System.IO.Directory.Exists(aimPath))
83 {
84 System.IO.Directory.CreateDirectory(aimPath);
85 }
86 // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
87 // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
88 // string[] fileList = Directory.GetFiles(srcPath);
89 string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
90 // 遍历所有的文件和目录
91 foreach (string file in fileList)
92 {
93 // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
94 if (System.IO.Directory.Exists(file))
95 {
96 CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
97 }
98 // 否则直接Copy文件
99 else
100 {
101 System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
102 }
103 }
104 }
105 catch (Exception e)
106 {
107 throw;
108 }
109 }