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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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);
  }
}

Method 2

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));
        }
    }

Method 3

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).

Method 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

Method 5

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 🙂

Method 6

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.

Method 7

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)));
        }
    }
}

Method 8

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!

Method 9

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"));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x