How to copy a folder recursively in C#

0
Categories: .NET, C#, Linux
Posted on: 5th May 2009 by: Andrei

using System;
using System.IO;

namespace cpFolder
{
	class Program
	{
		static void Main( string[] args )
		{
			copyFolder( @"C:\source", @"C:\destination" );
            Console.ReadLine();
        }
        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 );
            }
        }
    }
}