Copy the entire contents of a directory in C#

前端 未结 22 856
日久生厌
日久生厌 2020-11-22 07:13

I want to copy the entire contents of a directory from one location to another in C#.

There doesn\'t appear to be a way to do this using System.IO class

22条回答
  •  难免孤独
    2020-11-22 07:24

    If you like Konrad's popular answer, but you want the source itself to be a folder under target, rather than putting it's children under the target folder, here's the code for that. It returns the newly created DirectoryInfo, which is handy:

    public static DirectoryInfo CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
    {
      var newDirectoryInfo = target.CreateSubdirectory(source.Name);
      foreach (var fileInfo in source.GetFiles())
        fileInfo.CopyTo(Path.Combine(newDirectoryInfo.FullName, fileInfo.Name));
    
      foreach (var childDirectoryInfo in source.GetDirectories())
        CopyFilesRecursively(childDirectoryInfo, newDirectoryInfo);
    
      return newDirectoryInfo;
    }
    

提交回复
热议问题