Click here to Skip to main content
11,707,167 members (56,473 online)
Click here to Skip to main content

Function to copy a directory to another place (nothing fancy)

, 19 Nov 2002 311.4K 2K 61
Rate this:
Please Sign up or sign in to vote.
Simple C#/.NET tip to copy an entire directory tree to another directory

Introduction

I have been working with the .NET framework for several weeks now and I really enjoy the API. But sometimes I miss some features I need right now, even if I expect the framework to grow and get new classes and capabilities in the forthcoming versions (like Java did).

This article doesn't try to teach something but just gives a solution to anyone who needs it. I tried to keep it simple with few lines of code.

The FileSystem class

This class includes high level functions missing in the standard System.IO namespace. The class provided here only includes a directory to directory copy function for the moment, and the purpose of this article is to fix this .NET missing feature that many VB developers (for example) are used to.

The function takes two absolute paths (source directory and destination directory) as parameters and returns a boolean equal to true when the copy succeeds. Please note that this function automatically overwrites a destination file with the same name. Of course all subdirectories are also copied recursively.

using System;
using System.IO;

namespace Utility.IO{
    /// <summary>
    /// Filesystem
    /// </summary>
    public class FileSystem{
        // Copy directory structure recursively
        public static void copyDirectory(string Src,string Dst){
            String[] Files;

            if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar) 
                Dst+=Path.DirectorySeparatorChar;
            if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            Files=Directory.GetFileSystemEntries(Src);
            foreach(string Element in Files){
                // Sub directories
                if(Directory.Exists(Element)) 
                    copyDirectory(Element,Dst+Path.GetFileName(Element));
                // Files in directory
                else 
                    File.Copy(Element,Dst+Path.GetFileName(Element),true);
                }
            }

        }
    }

An usage example

Here is an example of how to use the FileSystem class.

// After a successful copy, you can then call 
// Directory.Delete(@"c:\MySrcDirectory") to mimic a Directory.Move behaviour
try{
    copyDirectory(@"c:\MySrcDirectory",@"c:\MyDstDirectory");
    }
catch(Exception Ex){
    Console.Error.WriteLine(Ex.Message);
    }

Conclusion

This article is just a tip targeted to beginners or newcomers who noticed this missing feature in the .NET framework. It is provided as a possible solution, but I encourage anyone to write his own function.

Happy Coding !!!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

GriffonRL
Software Developer (Senior) Siliconz Ltd
New Zealand New Zealand
Richard Lopes
Just Programmer

You may also be interested in...

Comments and Discussions

 
QuestionSo Elegantttttt.... Pin
shiwanijaiswal9-Mar-14 19:21
membershiwanijaiswal9-Mar-14 19:21 
QuestionSweet! Pin
Member 103752903-Jan-14 12:30
professionalMember 103752903-Jan-14 12:30 
GeneralThank You Pin
Member 996046223-May-13 13:12
memberMember 996046223-May-13 13:12 
GeneralThank You Pin
Member 996046223-May-13 13:09
memberMember 996046223-May-13 13:09 
GeneralMy vote of 5 Pin
susindhran19-Jun-12 9:03
membersusindhran19-Jun-12 9:03 
QuestionAll is well Pin
Krishnachytanya Ayyagari12-Dec-11 1:51
memberKrishnachytanya Ayyagari12-Dec-11 1:51 
GeneralMy vote of 2 Pin
euggg1234567821-Jul-11 0:27
membereuggg1234567821-Jul-11 0:27 
GeneralGood Article !!!!!!! :-) Pin
Suchitass11-May-11 1:02
memberSuchitass11-May-11 1:02 
GeneralMy vote of 5 Pin
Murat TARKUN7-Nov-10 7:51
memberMurat TARKUN7-Nov-10 7:51 
GeneralMicrosoft.VisualBasic.FileIO.FileSystem.CopyDirectory Pin
Vercas16-Oct-10 10:02
memberVercas16-Oct-10 10:02 
Generalthanks for saving peoples time. Pin
Behrooz_cs22-Apr-10 21:06
memberBehrooz_cs22-Apr-10 21:06 
Generalan easier way, non recursive Pin
kalvarez216-Dec-09 12:59
memberkalvarez216-Dec-09 12:59 
GeneralRe: an easier way, non recursive Pin
drweb8630-May-11 21:50
memberdrweb8630-May-11 21:50 
GeneralPlease use C# Pin
Jasper4C#20-Jul-09 2:41
memberJasper4C#20-Jul-09 2:41 
GeneralRe: Please use C# Pin
Member 128588620-Feb-11 12:49
memberMember 128588620-Feb-11 12:49 
GeneralSmall fix Pin
Member 404930514-Jul-08 22:50
memberMember 404930514-Jul-08 22:50 
You would like to check if the destination is a sub directory of the source. Otherwise you'll get an infinite loop, which will fill up your disk completely in minutes. Sigh | :sigh: This is one solution: (sorry I renamed the variable names to company standards)

public static void CopyDirectory(string src, string dst)
     {
         String[] files;
 
         if (dst[dst.Length - 1] != Path.DirectorySeparatorChar)
             dst += Path.DirectorySeparatorChar;
         if (!Directory.Exists(dst))
             Directory.CreateDirectory(dst);
 
         files = Directory.GetFileSystemEntries(src);
 
         foreach (string element in files)
         {
 
             if (Directory.Exists(element))
             {
                 // Sub directories
                 if (element + Path.DirectorySeparatorChar != dst)
                 {
                     CopyDirectory(element, dst + Path.GetFileName(element));
                 }
             }
             else
             {
                 // Files in directory
                 File.Copy(element, dst + Path.GetFileName(element), true);
             }
         }
     }

GeneralRe: Small fix Pin
chinese_zmm24-Mar-09 23:27
memberchinese_zmm24-Mar-09 23:27 
GeneralMissing error handling Pin
Tzipi Levy30-Apr-08 0:44
memberTzipi Levy30-Apr-08 0:44 
GeneralThank you Pin
ubshreenath24-Sep-07 8:44
memberubshreenath24-Sep-07 8:44 
GeneralOdd Things Pin
Spencerja7-Sep-07 4:13
memberSpencerja7-Sep-07 4:13 
GeneralExclude file Pin
GC9N6-Jun-07 4:34
memberGC9N6-Jun-07 4:34 
GeneralThank you! Pin
kabbykray3-Jun-07 18:29
memberkabbykray3-Jun-07 18:29 
GeneralSimpler one, based on string only Pin
nantcom24-Dec-06 5:22
membernantcom24-Dec-06 5:22 
GeneralRe: Simpler one, based on string only Pin
Wernight8-Jul-08 22:55
memberWernight8-Jul-08 22:55 
GeneralGood Article Pin
KingTermite20-Jun-05 10:05
memberKingTermite20-Jun-05 10:05 
GeneralRe: Good Article Pin
GriffonRL20-Jun-05 21:10
memberGriffonRL20-Jun-05 21:10 
GeneralEnhance to get file filter, sample call //copyDirectory(@&quot;c:\temp&quot;,@&quot;c:\temp\new&quot;, &quot;*e.exe;*l.xml&quot;); Pin
li hai3-Feb-05 5:57
memberli hai3-Feb-05 5:57 
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@&quot;c:\temp&quot;,@&quot;c:\temp\new&quot;, &quot;*e.exe;*l.xml&quot;); Pin
GriffonRL20-Jun-05 21:11
memberGriffonRL20-Jun-05 21:11 
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@&quot;c:\temp&quot;,@&quot;c:\temp\new&quot;, &quot;*e.exe;*l.xml&quot;); Pin
Steed Soft9-May-06 23:04
memberSteed Soft9-May-06 23:04 
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@&quot;c:\temp&quot;,@&quot;c:\temp\new&quot;, &quot;*e.exe;*l.xml&quot;); Pin
tirumal123128-Dec-06 19:27
membertirumal123128-Dec-06 19:27 
AnswerRe: Enhance to get file filter, sample call //copyDirectory(@&amp;amp;quot;c:\temp&amp;amp;quot;,@&amp;amp;quot;c:\temp\new&amp;amp;quot;, &amp;amp;quot;*e.exe;*l.xml&amp;amp;quot;); Pin
Steed Soft28-Dec-06 21:16
memberSteed Soft28-Dec-06 21:16 
GeneralEnhance to get file filter, sample call Pin
li hai3-Feb-05 5:57
memberli hai3-Feb-05 5:57 
QuestionHow about mapped drives? Pin
otc4-Aug-04 7:51
sussotc4-Aug-04 7:51 
AnswerRe: How about mapped drives? Pin
bass4g0d23-Oct-08 6:41
memberbass4g0d23-Oct-08 6:41 
GeneralLittle help required ! Pin
vikas123423-Mar-04 3:30
sussvikas123423-Mar-04 3:30 
GeneralVB.NET Version Pin
starlogic8-Feb-04 13:56
memberstarlogic8-Feb-04 13:56 
GeneralRe: VB.NET Version Pin
korcutt27-Apr-06 11:28
memberkorcutt27-Apr-06 11:28 
QuestionHow to determine drive types Pin
liuhoihing17-Nov-03 19:36
memberliuhoihing17-Nov-03 19:36 
AnswerRe: How to determine drive types Pin
chinese_zmm24-Mar-09 23:18
memberchinese_zmm24-Mar-09 23:18 
AnswerRe: How to determine drive types Pin
FrozenHearted25-Mar-09 23:34
memberFrozenHearted25-Mar-09 23:34 
QuestionWhy this way? Pin
Mustafa Demirhan19-Nov-02 15:54
memberMustafa Demirhan19-Nov-02 15:54 
AnswerRe: Why this way? Pin
GriffonRL19-Nov-02 21:35
memberGriffonRL19-Nov-02 21:35 
GeneralRe: Why this way? Pin
Mustafa Demirhan20-Nov-02 0:18
memberMustafa Demirhan20-Nov-02 0:18 
GeneralRe: Why this way? Pin
GriffonRL20-Nov-02 1:24
memberGriffonRL20-Nov-02 1:24 
GeneralRe: Why this way? Pin
BarryJ21-Nov-02 5:09
memberBarryJ21-Nov-02 5:09 
GeneralRe: Why this way? Pin
GriffonRL21-Nov-02 5:45
memberGriffonRL21-Nov-02 5:45 
GeneralGreat article... Pin
David Stone19-Nov-02 5:13
memberDavid Stone19-Nov-02 5:13 
GeneralRe: Great article... Pin
GriffonRL19-Nov-02 5:42
memberGriffonRL19-Nov-02 5:42 
GeneralRe: Great article... Pin
David Stone19-Nov-02 15:32
memberDavid Stone19-Nov-02 15:32 
GeneralRe: Great article... Pin
Mustafa Demirhan19-Nov-02 15:51
memberMustafa Demirhan19-Nov-02 15:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 20 Nov 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid