• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

文件与文件夹的完全复制

开发技术 开发技术 2周前 (04-29) 7次浏览

文件与文件夹的完全复制,包扩子目录与子目录的文件

static void Main(string[] args)
        {
            string dir1 = @"E:我的学习2.NETFileAndDirCopyfile1";
            string dir2 = @"E:我的学习2.NETFileAndDirCopyfile2";

            FileAndDirFullCopy(dir1, dir2);

            Console.ReadKey();
        }

        /// <summary>
        /// Full copies of files and directories
        /// </summary>
        /// <param name="sourceDir">source Dir.</param>
        /// <param name="destinationDir">destination Dir.</param>
        public static void FileAndDirFullCopy(string sourceDir, string destinationDir)
        {
            DirectoryInfo source = new DirectoryInfo(sourceDir);

            //Files
            FileInfo[] sonfiles = source.GetFiles();
            foreach (var sonfile in sonfiles)
            {
                string copyToSonFile = Path.Combine(destinationDir, sonfile.Name);
                if (!File.Exists(copyToSonFile))
                {
                    sonfile.CopyTo(copyToSonFile);
                    Console.WriteLine($"文件:({sonfile.FullName})被复制到({copyToSonFile}).r");
                }

                Console.WriteLine($"文件:({sonfile.FullName})复制结束.");
            }

            //Directories and subfolders and subfiles
            DirectoryInfo[] sonDirs = source.GetDirectories();
            foreach (var sonDir in sonDirs)
            {
                //Directories
                string copyToSonDir = Path.Combine(destinationDir, sonDir.Name);
                if (!Directory.Exists(copyToSonDir))
                {
                    Console.WriteLine($"目录:{sonDir.FullName},被创建.r");
                    Directory.CreateDirectory(copyToSonDir);
                }

                //subfolders 
                FileInfo[] sonSonfiles = sonDir.GetFiles();
                foreach (var sonSonfile in sonSonfiles)
                {
                    string copyToSonSonFile = Path.Combine(copyToSonDir, sonSonfile.Name);
                    if (!File.Exists(copyToSonSonFile))
                    {
                        sonSonfile.CopyTo(copyToSonSonFile);
                        Console.WriteLine($"文件:({sonSonfile.FullName})被复制到({copyToSonSonFile}).r");
                    }
                }

                //subfiles
                FileAndDirFullCopy(sonDir.FullName, copyToSonDir);

                Console.WriteLine($"目录:({sonDir.FullName})复制结束.");
                Console.WriteLine();
            }
        }

程序员灯塔
转载请注明原文链接:文件与文件夹的完全复制
喜欢 (0)