Copy the entire contents of a directory in C#

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

    Copy folder recursively without recursion to avoid stack overflow.

    public static void CopyDirectory(string source, string target)
    {
        var stack = new Stack();
        stack.Push(new Folders(source, target));
    
        while (stack.Count > 0)
        {
            var folders = stack.Pop();
            Directory.CreateDirectory(folders.Target);
            foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
            {
                File.Copy(file, Path.Combine(folders.Target, Path.GetFileName(file)));
            }
    
            foreach (var folder in Directory.GetDirectories(folders.Source))
            {
                stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
            }
        }
    }
    
    public class Folders
    {
        public string Source { get; private set; }
        public string Target { get; private set; }
    
        public Folders(string source, string target)
        {
            Source = source;
            Target = target;
        }
    }
    

提交回复
热议问题