6

How do I copy a directory to a different drive in C#?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Govind Malviya
  • 13,627
  • 17
  • 68
  • 94
  • 2
    lol, what? Sorry not making fun of anyone just thought this question is hilarious the way it is asked :) – VoodooChild Jun 01 '10 at 04:43
  • I understand that the question has been answered, but you should try and improve the quality of the question. It's not very well written. – Alastair Pitts Jun 01 '10 at 04:46
  • 3
    I think we need a new reason to close - 'easy to find if the OP makes the effort' – Gishu Jun 01 '10 at 04:59
  • i I have checked your 'user details' and found that you are new, I don't want demoralize you because same thing happened with me, when I was new to stackoverflow, this is really very good community for programmers, You just first try to search topics on google and if you not found any solution their, then only put your question here, also put the code which you have written to do this task(if you have). – Dr. Rajesh Rolen Jun 16 '10 at 14:47

6 Answers6

16

You can use this code to perform your operation:

public static  void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    // Check if the target directory exists, if not, create it.
    if (Directory.Exists(target.FullName) == false)
    {
        Directory.CreateDirectory(target.FullName);
    }

    // Copy each file into it’s new directory.
    foreach (FileInfo fi in source.GetFiles())
    {
        Console.WriteLine(@”Copying {0}\{1}”, target.FullName, fi.Name);
        fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
    }

    // Copy each subdirectory using recursion.
    foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
    {
        DirectoryInfo nextTargetSubDir =
            target.CreateSubdirectory(diSourceSubDir.Name);
        CopyAll(diSourceSubDir, nextTargetSubDir);
    }
}

below one is also good:

    static public void CopyFolder( string sourceFolder, string destFolder )
    {
        if (!Directory.Exists( destFolder ))
            Directory.CreateDirectory( destFolder );
        string[] files = Directory.GetFiles( sourceFolder );
        foreach (string file in files)
        {
            string name = Path.GetFileName( file );
            string dest = Path.Combine( destFolder, name );
            File.Copy( file, dest );
        }
        string[] folders = Directory.GetDirectories( sourceFolder );
        foreach (string folder in folders)
        {
           string name = Path.GetFileName( folder );
           string dest = Path.Combine( destFolder, name );
            CopyFolder( folder, dest );
        }
    }

you can use this function also:

FileSystem.CopyDirectory(sourceDir, destDir);
Bobby
  • 11,419
  • 5
  • 44
  • 69
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
6
FileSystem.CopyDirectory(sourceDir, destDir);

FileSystem.CopyDirectory is in a VB namespace and assembly, but that probably doesn't matter.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
2

How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/cc148994.aspx

C# Copy Folder Recursively
http://www.csharp411.com/c-copy-folder-recursively/

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
2

Here's an extension that will work in .NET 4.0+

var source = new DirectoryInfo(@"C:\Test");
var destination = new DirectoryInfo(@"E:\Test");
source.CopyTo(destination);

Include this file in your project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace System.IO
{
  public static class DirectoryInfoExtensions
  {
    public static void CopyTo(this DirectoryInfo source, DirectoryInfo target)
    {
      if (!target.Exists)
        target.Create();

      foreach (var file in source.GetFiles())
        file.CopyTo(Path.Combine(target.FullName, file.Name), true);

      foreach (var subdir in source.GetDirectories())
        subdir.CopyTo(target.CreateSubdirectory(subdir.Name));
    }
  }
}
Robear
  • 986
  • 1
  • 11
  • 15
0
    private String path;
    public int copyAllContents(String destinationFolder, ProgressBar progressBar)
    {
        int countCopyFiles = 0;
        if (!Directory.Exists(destinationFolder))
        { Directory.CreateDirectory(destinationFolder); }
        String[] allFilesForCurrentFolder = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
        String[] subFoldersAllpath = Directory.GetDirectories(path);
        for (int i = 0; i < allFilesForCurrentFolder.Length; i++)
        {
            try { File.Copy(allFilesForCurrentFolder[i], destinationFolder + "\\" + Path.GetFileName(allFilesForCurrentFolder[i])); countCopyFiles++; progressBar.Value++; }
            catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); }
        }
        if (subFoldersAllpath.Length == 0)
        { return allFilesForCurrentFolder.Length; };
        for (int i = 0; i < subFoldersAllpath.Length; i++)
        {
            this.path = subFoldersAllpath[i];
            String[] subFoldersAllpathLastFolder = subFoldersAllpath[i].Split('\\');
            countCopyFiles += this.copyAllContents(destinationFolder + "\\" + subFoldersAllpathLastFolder[subFoldersAllpathLastFolder.Length - 1], progressBar);
        }
        return countCopyFiles;
    }
  • It is much easier for others to read your answer if you format your code properly. Also, it is best to add some context to your code. Write about why you think this is a good answer or what it does differently than the other answers. – mdewitt Feb 08 '14 at 00:27
0

Here's an approach that copies a directory recursively as an async function:

public static async Task CopyDirectoryAsync(string sourceDirectory, string destinationDirectory)
{
    if (!Directory.Exists(destinationDirectory))
        Directory.CreateDirectory(destinationDirectory);

    foreach (var file in Directory.GetFiles(sourceDirectory))
    {
        var name = Path.GetFileName(file);
        var dest = Path.Combine(destinationDirectory, name);
        await CopyFileAsync(file, dest);
    }

    foreach (var subdir in Directory.GetDirectories(sourceDirectory))
    {
        var name = Path.GetFileName(subdir);
        var dest = Path.Combine(destinationDirectory, name);
        await CopyDirectoryAsync(subdir, dest);
    }
}

public static async Task CopyFileAsync(string sourceFile, string destinationFile)
{
    using (var sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
    using (var destinationStream = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
        await sourceStream.CopyToAsync(destinationStream);
}
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742