Copy the entire contents of a directory in C#

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

    This site always have helped me out a lot, and now it's my turn to help the others with what I know.

    I hope that my code below be useful for someone.

    string source_dir = @"E:\";
    string destination_dir = @"C:\";
    
    // substring is to remove destination_dir absolute path (E:\).
    
    // Create subdirectory structure in destination    
        foreach (string dir in System.IO.Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
        {
            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destination_dir, dir.Substring(source_dir.Length + 1)));
            // Example:
            //     > C:\sources (and not C:\E:\sources)
        }
    
        foreach (string file_name in System.IO.Directory.GetFiles(source_dir, "*", System.IO.SearchOption.AllDirectories))
        {
            System.IO.File.Copy(file_name, System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length + 1)));
        }
    

提交回复
热议问题