Copy the entire contents of a directory in C#

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

    My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer.

    public static void CopyEntireDirectory(string path, string newPath)
    {
        Parallel.ForEach(Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories)
        ,(fileName) =>
        {
            string output = Regex.Replace(fileName, "^" + Regex.Escape(path), newPath);
            if (File.Exists(fileName))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(output));
                File.Copy(fileName, output, true);
            }
            else
                Directory.CreateDirectory(output);
        });
    }
    

    EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.

    public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
    {
        if (!source.Exists) return;
        if (!target.Exists) target.Create();
    
        Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>
            CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));
    
        Parallel.ForEach(source.GetFiles(), sourceFile =>
            sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));
    }
    

提交回复
热议问题