.NET Directory Copy() Method

I’ll never understand why Microsoft thought a Copy() method for the Directory class wasn’t necessary (but one for the File class was). I love the .NET Framework, but come on, guys! How could this not be important?!

This is just for my reference (or anyone else that needs it). I wrote this little function a while back when I experimented with a few things on the Web site. I needed it again a few days ago when writing an app for work, but I didn’t have it in the office. Being the ever lazy person I am, I’m putting it here so that I can copy and paste it when I need it again:

public static void CopyDirectory(string source, string destination)
{
string[] files;
// Make sure the destination ends with ‘\’
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
destination += Path.DirectorySeparatorChar;

if (!Directory.Exists(destination))
Directory.CreateDirectory(destination);

files = Directory.GetFileSystemEntries(source);
foreach (string element in files)
{
// Sub-directories
if (Directory.Exists(element))
CopyDirectory(element,destination + Path.GetFileName(element));
// Files in current directory
else
File.Copy(element,destination + Path.GetFileName(element),true);
}
}
8/1/2005 12:00:00 AM | Tags: .NET, C#
© 2008 Jeremy McPeak