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目录下。

相关文章:

  • 2022-12-23
  • 2021-09-12
  • 2021-07-17
  • 2021-10-31
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-07-06
  • 2018-08-16
  • 2022-01-29
  • 2018-08-18
相关资源
相似解决方案