Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Folders in C# using System.IO

I need to Copy folder C:\FromFolder to C:\ToFolder

Below is code that will CUT my FromFolder and then will create my ToFolder. So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder

System.IO.Directory.Move(@"C:\FromFolder ", @"C:\ToFolder");

But i just want to Copy the files in FromFolder to ToFolder. For some reason there is no System.IO.Directory.Copy???

How this is done using a batch file - Very easy

xcopy C:\FromFolder C:\ToFolder

Regards Etienne

like image 288
Etienne Avatar asked Mar 24 '09 12:03

Etienne


2 Answers

This link provides a nice example.

http://msdn.microsoft.com/en-us/library/cc148994.aspx

Here is a snippet

// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
//       in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
  string[] files = System.IO.Directory.GetFiles(sourcePath);

  // Copy the files and overwrite destination files if they already exist.
  foreach (string s in files)
  {
    // Use static Path methods to extract only the file name from the path.
    fileName = System.IO.Path.GetFileName(s);
    destFile = System.IO.Path.Combine(targetPath, fileName);
    System.IO.File.Copy(s, destFile, true);
  }
}
like image 93
bendewey Avatar answered Sep 22 '22 07:09

bendewey


there is a file copy. Recreate folder and copy all the files from original directory to the new one example

static void Main(string[] args)
    {
        DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
        DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");

        CopyDirectory(sourceDir, destinationDir);

    }

    static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
    {
        if (!destination.Exists)
        {
            destination.Create();
        }

        // Copy all files.
        FileInfo[] files = source.GetFiles();
        foreach (FileInfo file in files)
        {
            file.CopyTo(Path.Combine(destination.FullName, 
                file.Name));
        }

        // Process subdirectories.
        DirectoryInfo[] dirs = source.GetDirectories();
        foreach (DirectoryInfo dir in dirs)
        {
            // Get destination directory.
            string destinationDir = Path.Combine(destination.FullName, dir.Name);

            // Call CopyDirectory() recursively.
            CopyDirectory(dir, new DirectoryInfo(destinationDir));
        }
    }
like image 43
RvdK Avatar answered Sep 23 '22 07:09

RvdK