Copy the entire contents of a directory in C#

前端 未结 22 1260
日久生厌
日久生厌 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:33

    Here is an extension method for DirectoryInfo a la FileInfo.CopyTo (note the overwrite parameter):

    public static DirectoryInfo CopyTo(this DirectoryInfo sourceDir, string destinationPath, bool overwrite = false)
    {
        var sourcePath = sourceDir.FullName;
    
        var destination = new DirectoryInfo(destinationPath);
    
        destination.Create();
    
        foreach (var sourceSubDirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
            Directory.CreateDirectory(sourceSubDirPath.Replace(sourcePath, destinationPath));
    
        foreach (var file in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories))
            File.Copy(file, file.Replace(sourcePath, destinationPath), overwrite);
    
        return destination;
    }
    

提交回复
热议问题