Click here to Skip to main content
15,888,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please give a c# code for copy files and folders(including sub folders) from one location to another location.
Posted
Updated 13-Aug-13 17:00pm
v2

1 solution

Hello,
Please try this.

C#
using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        DirectoryInfo[] dirs = dir.GetDirectories();

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}
 
Share this answer
 
Comments
Sushil Mate 14-Aug-13 0:10am    
Try to add the source/link in your answer where you copied this snippet. it might lead to plagiarisation.

http://msdn.microsoft.com/en-us/library/bb762914.aspx
Elk Cloner 16-Aug-13 4:24am    
The above code is working, but no indication for copy, when a huge volume of data. Please give me a solution for solve that problem?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900