首页 > Windows开发 > 详细

c#复制包含子目录文件夹代码

时间:2016-04-16 00:46:45      阅读:262      评论:0      收藏:0      [点我收藏+]

c#没有复制目录的代码,需要通过递归实现复制目录:

需要引用System.IO命名空间,实现代码如下:

private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)  
{  
   bool ret = false;  
   try  
   {  
       SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";  
       DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";  

       if (Directory.Exists(SourcePath))  
       {  
           if (Directory.Exists(DestinationPath) == false)  
               Directory.CreateDirectory(DestinationPath);  

           foreach (string fls in Directory.GetFiles(SourcePath))  
           {  
               FileInfo flinfo = new FileInfo(fls);  
               flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);  
           }  
           foreach (string drs in Directory.GetDirectories(SourcePath))  
           {  
               DirectoryInfo drinfo = new DirectoryInfo(drs);  
               if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)  
                   ret = false;  
           }  
       }  
       ret = true;  
   }  
   catch (Exception ex)  
   {  
       ret = false;  
   }  
   return ret;  
}

使用方法:

bool copy = CopyDirectory("c:\\temp\\index\\", "c:\\temp\\newindex\\", true);

上面的方法将把c:\temp\index目录下的所有子目录和文件复制到 c:\temp\newindex目录下。

c#复制包含子目录文件夹代码

原文:http://www.cnblogs.com/meetrice/p/5397289.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!