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))
            {
                Directory.CreateDirectory(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);
                sourceSubDir.CopyTo(targetSubDir);
            }
        }
    }

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 comment

Blog at WordPress.com.