Geeks With Blogs
Wil Peck Experience is something you get right after you need it.

The .NET Framework does not offer support for a directory copy method OOB.  Fortunately in .NET 3.5 we can decorate the DirectoryInfo method with our own CopyTo method using an extension method.  See the below example…

public static class DirectoryInfoExtensions
{
    public static void CopyTo(this DirectoryInfo source, string rootDestinationDirectory, bool recursive)
    {
        if (string.IsNullOrEmpty(rootDestinationDirectory))
        {
            throw new ArgumentNullException("destinationDirectory");
        }

        if (!Directory.Exists(rootDestinationDirectory))
        {
            Directory.CreateDirectory(rootDestinationDirectory);
        }

        string destinationDirectoryToCreate = Path.Combine(rootDestinationDirectory, source.Name);

        if (!Directory.Exists(destinationDirectoryToCreate))
        {
            Directory.CreateDirectory(destinationDirectoryToCreate);
        }

        foreach (string file in Directory.GetFiles(source.FullName))
        {
            File.Copy(file, Path.Combine(destinationDirectoryToCreate, Path.GetFileName(file)), true);
        }

        if (recursive)
        {
            foreach (DirectoryInfo directory in source.GetDirectories())
            {
                CopyTo(directory, destinationDirectoryToCreate, true);
            }
        }
    }

    public static void CopyTo(this DirectoryInfo source, string destinationDirectory)
    {
        CopyTo(source, destinationDirectory, false);
    }
}

Posted on Friday, September 11, 2009 9:46 AM | Back to top


Comments on this post: DirectoryInfo.CopyTo

# re: DirectoryInfo.CopyTo
Requesting Gravatar...
I don't believe you need to check for source == null, since that would not be possible. Not that it really matters ...
Left by Bill on Sep 11, 2009 2:41 PM

# re: DirectoryInfo.CopyTo
Requesting Gravatar...
HAHA, thanks - good point. By definition it wouldn't be available anyway. I think I just did it out of habit.
Left by Wil Peck on Sep 11, 2009 4:19 PM

Your comment:
 (will show your gravatar)


Copyright © Wil Peck | Powered by: GeeksWithBlogs.net