Copy the entire contents of a directory in C#

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

    This is my code hope this help

        private void KCOPY(string source, string destination)
        {
            if (IsFile(source))
            {
                string target = Path.Combine(destination, Path.GetFileName(source));
                File.Copy(source, target, true);
            }
            else
            {
                string fileName = Path.GetFileName(source);
                string target = System.IO.Path.Combine(destination, fileName);
                if (!System.IO.Directory.Exists(target))
                {
                    System.IO.Directory.CreateDirectory(target);
                }
    
                List files = GetAllFileAndFolder(source);
    
                foreach (string file in files)
                {
                    KCOPY(file, target);
                }
            }
        }
    
        private List GetAllFileAndFolder(string path)
        {
            List allFile = new List();
            foreach (string dir in Directory.GetDirectories(path))
            {
                allFile.Add(dir);
            }
            foreach (string file in Directory.GetFiles(path))
            {
                allFile.Add(file);
            }
    
            return allFile;
        }
        private bool IsFile(string path)
        {
            if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
            {
                return false;
            }
            return true;
        }
    

提交回复
热议问题