ASP.NET C# Copy Directory with SubDirectories with System.IO

前端 未结 3 667
醉酒成梦
醉酒成梦 2021-01-14 01:27

I need to copy a whole directory C:\\X to C:\\Y\\X, and I need the sub-folders to be copied as well.
Is there any way to do it with the System.IO.File\\Directory namespa

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 01:45

    This is copied from xneurons blog.

    public static void CopyAll(DirectoryInfo source, DirectoryInfo target) {
        // Check if the target directory exists, if not, create it.
        if (Directory.Exists(target.FullName) == false) {
            Directory.CreateDirectory(target.FullName);
        }
    
        // Copy each file into it’s new directory.
        foreach (FileInfo fi in source.GetFiles()) {
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
        }
    
        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
            DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
            CopyAll(diSourceSubDir, nextTargetSubDir);
        }
    }
    

提交回复
热议问题