18

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

Etienne
  • 7,141
  • 42
  • 108
  • 160

9 Answers9

20

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);
  }
}
bendewey
  • 39,709
  • 13
  • 100
  • 125
19

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));
        }
    }
RvdK
  • 19,580
  • 4
  • 64
  • 107
5

Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).

4

yes you are right.

http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx

has provided copy function .. or you can use another function

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

lakshmanaraj
  • 4,145
  • 23
  • 12
2

A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist

class Utils
{
    internal static void copy_dir(string source, string dest)
    {
        if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
        Directory.CreateDirectory(dest);
        foreach (string fn in Directory.GetFiles(source))
        {
            File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
        }
        foreach (string dir_fn in Directory.GetDirectories(source))
        {
            copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
        }
    }
}
Ramil Shavaleev
  • 364
  • 3
  • 12
2

You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.

string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
        fileName=Path.GetFileName(s);
        destFile = Path.Combine(DestinationPath, fileName);
        File.Copy(s, destFile);
}

I leave creating the destination directory to you :-)

Ian Jacobs
  • 5,456
  • 1
  • 23
  • 38
2

You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.

I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.

Jonathan van de Veen
  • 1,016
  • 13
  • 27
1

This article provides an alogirthm to copy recursively some folder and all its content

From the article :

Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.

Good luck!

Philippe
  • 1,733
  • 1
  • 14
  • 28
0

My version of DirectoryInfo.CopyTo using extension.

public static class DirectoryInfoEx {
    public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
        if (source.FullName.ToLower() == target.FullName.ToLower())
            return;

        if (!target.Exists)
            target.Create();

        foreach (FileInfo f in source.GetFiles()) {
            FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
            f.CopyTo(newFile.FullName, true);
        }

        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
            DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
            diSourceSubDir.CopyTo(nextTargetSubDir);
        }
    }
}

And use like that...

DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));
diegodsp
  • 882
  • 8
  • 12
  • How deep into the folder structure does this copy go? It looks like it will only copy subfolders - not sub-subfolders. It looks like the @RvdK solution is the only that is recursive. – Jag May 20 '13 at 15:49
  • This is recursive @Jag, in the last foreach the DirectoryInfo used for interate the sub-directories uses the same extension "CopyTo". ;P – diegodsp Mar 26 '15 at 17:50
  • Ah yes, I stand corrected. Must of had a blonde moment :) – Jag Mar 31 '15 at 12:17