且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#编程-27:复制文件和目录

更新时间:2022-05-29 11:01:30

  ///拷贝单个文件

           string fileName = "test.txt";

           string sourcePath = @"D:\source";

           string targetPath = @"D:\target";


           string sourceFile = Path.Combine(sourcePath,fileName);

           string destFile = Path.Combine(targetPath,fileName);


           if (!Directory.Exists(targetPath))

           {

               Directory.CreateDirectory(targetPath);

           }


           File.Copy(sourceFile,destFile,true);


           ///拷贝多个文件

           if (Directory.Exists(sourcePath))

           {

               string[] files = Directory.GetFiles(sourcePath);


               foreach (string s in files)

               {

                   fileName = Path.GetFileName(s);

                   destFile = Path.Combine(targetPath, fileName);

                   File.Copy(s, destFile, true);

               }


           }

           else {

               Console.WriteLine("source path dose not exist! ");

           }

           Console.WriteLine("press any key to exit.");

           Console.ReadKey();