Monday, July 11, 2011

C# - Copy files and folders recursively from source to destination folder in c-sharp

In C#, there is no built in function to recursively bulk-copy all files and folders from source to destination folder. So this has to be done manually by the programmer. Being a lover of reusability feature of object oriented programming, I googled and stumbled on the code snippet below:
/// 
    /// Copy folder to another folder recursively
    /// 
    /// /// public static 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);
        }
    }
Note that all files at the source folder have been copied to the destination folder. But folder and files within them have been copied using recursion - see the function of second foreach construct.

Shortcomings? Yes, no exception handling has been done in the snippet. However, the functionality is ok! Thanks to csharp411.com.

2 comments:

Anonymous said...

Thank you so much for the solution. helped me a lot.

Anonymous said...

Thanks for this perfect solution. I would only add the overwrite option in the file.copy parameters to avoid exceptions when the file already exists:

File.Copy(file, dest, true);

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles