Words on my addictions: .NET, Philosophy, Music

23 November 2007

DirectoryInfo.CopyTo Custom Extension in C# 3.0

Filed under: C# — Tags: — stefanprodan @ 4:46 pm

DirectoryInfo doesn’t have a method for recursive copying of files and subfoders from one root to another. The following code ads the CopyTo method to the DirectoryInfo class using the new C# 3.0 feature named code extensions.

    public static class Extensions
        public static void CopyTo(this DirectoryInfo source, DirectoryInfo target)
            if (!Directory.Exists(target.FullName))

            foreach (FileInfo fileInfo in source.GetFiles())
                fileInfo.CopyTo(Path.Combine(target.ToString(), fileInfo.Name), true);

            foreach (DirectoryInfo sourceSubDir in source.GetDirectories())
                DirectoryInfo targetSubDir = target.CreateSubdirectory(sourceSubDir.Name);

Include this static class in your project and then you can use it like this:

DirectoryInfo info = new DirectoryInfo(@”C:\temp”);
info.CopyTo( new DirectoryInfo(@”C:\Copy of temp”));

kick it on DotNetKicks.com


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: