Copy the entire contents of a directory in C#

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

    Copy and replace all files of the folder

            public static void CopyAndReplaceAll(string SourcePath, string DestinationPath, string backupPath)
        {
                foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory($"{DestinationPath}{dirPath.Remove(0, SourcePath.Length)}");
                    Directory.CreateDirectory($"{backupPath}{dirPath.Remove(0, SourcePath.Length)}");
                }
                foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
                {
                    if (!File.Exists($"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}"))
                        File.Copy(newPath, $"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}");
                    else
                        File.Replace(newPath
                            , $"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}"
                            , $"{ backupPath}{newPath.Remove(0, SourcePath.Length)}", false);
                }
        }
    

提交回复
热议问题