Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Usuful methods – 11 of N – Copy/Move Directory September 12, 2008

Today I have to copy an entire directory including all files, sub directories and all sub files to another directory. The .NET framework doesn’t provide such method (at least I don’t know of it) so I have coded one myself. Here’s the implementation of the CopyDirectory method.

        public static void CopyDirectory(string source, string destination)
        {
            if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
            {
                destination += Path.DirectorySeparatorChar;
            }
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            var entries = Directory.GetFileSystemEntries(source);
            foreach (var e in entries)
            {
                if (Directory.Exists(e))
                {
                    CopyDirectory(e, destination + Path.GetFileName(e));
                }
                else
                {
                    File.Copy(e, destination + Path.GetFileName(e), true);
                }
            }
        }

MoveDirectory is very simple when we have CopyDirectory. I know it’s not as fast as it can be ( if we use File.Move()) but still it gets the job done.

        public static void MoveDirectory(string source, string destination)
        {
            CopyDirectory(source, destination);
            Directory.Delete(source);
        }