C#.NET实现文件夹的复制

 1 只提供了文件的Copy方法,但却没有提供文件夹的Copy方法,经过一天的努力,终于搞定。现贴出主要代码供大家参考,欢迎大家提出建议。代码如下: public int DirectoryName(string DirectoryPath)//获取文件夹名,截取“\” 
2   {
3   int j = 0; char[] c = DirectoryPath.ToCharArray();
4   for (int i = c.Length - 1; i >= 0; i--)//从后面截取
5   {
6   j = i;
7   if (c == '\\')
8   {
9   break;//遇"\"调处,并返回"\"的位置
10   }
11   }
12   return j+1;
13   }
14   public void CopyDirectory(string DirectoryPath,string DirAddress)//复制文件夹,
15   {
16   #region//递归
17   string s = DirectoryPath.Substring(DirectoryName(DirectoryPath));//获取文件夹名
18   if (Directory.Exists(DirAddress + "\\" + s))
19   {
20   Directory.Delete(DirAddress + "\\" + s,true);//若文件夹存在,不管目录是否为空,删除
21   Directory.CreateDirectory(DirAddress + "\\" + s);//删除后,重新创建文件夹
22   }
23   else
24   {
25   Directory.CreateDirectory(DirAddress + "\\" + s);//文件夹不存在,创建
26   }
27   DirectoryInfo DirectoryArray = new DirectoryInfo(DirectoryPath);
28   FileInfo[] Files = DirectoryArray.GetFiles();//获取该文件夹下的文件列表
29   DirectoryInfo[] Directorys = DirectoryArray.GetDirectories();//获取该文件夹下的文件夹列表
30   foreach (FileInfo inf in Files)//逐个复制文件
31   {
32   File.Copy(DirectoryPath + "\\" + inf.Name, DirAddress + "\\" + s + "\\" + inf.Name);
33   }
34   foreach (DirectoryInfo Dir in Directorys)//逐个获取文件夹名称,并递归调用方法本身
35   {
36   CopyDirectory(DirectoryPath + "\\" + Dir.Name, DirAddress + "\\" + s);
37   }
38   #endregion
39   }
40
41   以上是已经通过检验成功的代码,是通过递归的方式来逐个复制文件和创建文件夹.还一种方法是通过使用DOS命令行来实现的,可是不知道为什么同样的命令行,我在CMD中使用可以,在程序中就不行呢,请指教。
42   以下是代码: #region 
43 //方法一OS命令:xcopy c:\docume~1\andy e:\andy /s/e 未实现
44   string s = DirectoryPath.Substring(DirectoryName(DirectoryPath));//获取文件夹名
45   Directory.CreateDirectory(DirAddress + "\\" + s);//创建文件夹
46   System.Diagnostics.Process process = new System.Diagnostics.Process();
47   process.StartInfo.FileName = "cmd";
48   process.StartInfo.Arguments = "xcopy \"" + DirectoryPath + "\" \"" + DirAddress + "\\" + s + "\" /s/e";
49   process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
50   process.StartInfo.CreateNoWindow = true;
51   process.StartInfo.UseShellExecute = false;
52   process.StartInfo.RedirectStandardOutput = true;
53   process.Start();
54   process.WaitForExit();
55   #endregion

 

你可能感兴趣的:(.net)