C# 目录(文件夹)复制实现

 1         private static void CopyDir(DirectoryInfo origin, string target)
 2         {
 3             if (!target.EndsWith("\\"))
 4             {
 5                 target += "\\";
 6             }
 7             if (!Exist(target))
 8             {
 9                 Create(target);
10                 //Create(target, origin.GetAccessControl());
11             }
12             FileInfo[] fileList = origin.GetFiles();
13             DirectoryInfo[] dirList = origin.GetDirectories();
14             foreach (FileInfo fi in fileList)
15             {
16                 File.Copy(fi.FullName, target + fi.Name, true);
17             }
18             foreach (DirectoryInfo di in dirList)
19             {
20                 CopyDir(di, target + di.Name);
21             }
22             DirectoryInfo tmp = new DirectoryInfo(target);
23             tmp.Attributes = origin.Attributes;
24             tmp.SetAccessControl(origin.GetAccessControl());
25         }
26 
27         private static void CopyDir(string origin, string target)
28         {
29             if (!origin.EndsWith("\\"))
30             {
31                 origin += "\\";
32             }
33             if (!target.EndsWith("\\"))
34             {
35                 target += "\\";
36             }
37 
38             DirectoryInfo info = new DirectoryInfo(origin);
39             if (!Exist(target))
40             {
41                 Create(target,info.GetAccessControl());//创建目录,访问权限
42             }
43 
44             FileInfo[] fileList = info.GetFiles();
45             DirectoryInfo[] dirList = info.GetDirectories();
46             foreach (FileInfo fi in fileList)
47             {
48                 File.Copy(fi.FullName, target + fi.Name, true);
49             }
50             foreach (DirectoryInfo di in dirList)
51             {
52                 //CopyDir(origin + "\\" + di.Name, target + "\\" + di.Name);
53                 CopyDir(di.FullName, target + "\\" + di.Name);
54             }
55             //设置目录属性和访问权限
56             DirectoryInfo tmp = new DirectoryInfo(target);
57             tmp.Attributes = info.Attributes;
58             tmp.SetAccessControl(info.GetAccessControl());
59         }

 

知识共享许可协议
本作品由SeayXu创作,采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
基于http://www.cnblogs.com/seayxu上的作品创作。
可自由转载、引用,但需署名作者且注明文章出处,并以相同方式共享。
posted @ 2015-07-10 10:33  seayxu  阅读(2407)  评论(0编辑  收藏  举报