c#复制文件、文件夹代码

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

使用方法:

1、把c:\temp\index目录下的所有子目录和文件复制到 c:\temp\newindex目录下。

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

2、具体代码实现

需要引用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;  
}
3、直接把代码拷贝到你的程序就大功告成

以上仅为记录,转载来源为:https://www.cnblogs.com/meetrice/p/5397289.html
posted @   火线码猿  阅读(17114)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示