Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 1.46 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do you copy all content of one folder( copy files and folders)
  2. using System;
  3. using System.IO;
  4.  
  5. class CopyDir
  6. {
  7.     public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
  8.     {
  9.         if (source.FullName.ToLower() == target.FullName.ToLower())
  10.         {
  11.             return;
  12.         }
  13.  
  14.         // Check if the target directory exists, if not, create it.
  15.         if (Directory.Exists(target.FullName) == false)
  16.         {
  17.             Directory.CreateDirectory(target.FullName);
  18.         }
  19.  
  20.         // Copy each file into it's new directory.
  21.         foreach (FileInfo fi in source.GetFiles())
  22.         {
  23.             Console.WriteLine(@"Copying {0}{1}", target.FullName, fi.Name);
  24.             fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
  25.         }
  26.  
  27.         // Copy each subdirectory using recursion.
  28.         foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
  29.         {
  30.             DirectoryInfo nextTargetSubDir =
  31.                 target.CreateSubdirectory(diSourceSubDir.Name);
  32.             CopyAll(diSourceSubDir, nextTargetSubDir);
  33.         }
  34.     }
  35.  
  36.     public static void Main()
  37.     {
  38.         string sourceDirectory = @"c:sourceDirectory";
  39.         string targetDirectory = @"c:targetDirectory";
  40.  
  41.         DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
  42.         DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
  43.  
  44.         CopyAll(diSource, diTarget);
  45.     }
  46.  
  47.     // Output will vary based on the contents of the source directory.
  48. }