Copy the entire contents of a directory in C#

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

    tboswell 's replace Proof version (which is resilient to repeating pattern in filepath)

    public static void copyAll(string SourcePath , string DestinationPath )
    {
       //Now Create all of the directories
       foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
          Directory.CreateDirectory(Path.Combine(DestinationPath ,dirPath.Remove(0, SourcePath.Length ))  );
    
       //Copy all the files & Replaces any files with the same name
       foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",  SearchOption.AllDirectories))
          File.Copy(newPath, Path.Combine(DestinationPath , newPath.Remove(0, SourcePath.Length)) , true);
        }
    

提交回复
热议问题