Click here to Skip to main content
Licence 
First Posted 18 Nov 2002
Views 258,766
Bookmarked 55 times

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

By | 19 Nov 2002 | Article
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

About the Author

GriffonRL

Software Developer (Senior)
Siliconz Ltd
New Zealand New Zealand

Member

Richard Lopes
Just Programmer

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionAll is well PinmemberKrishnachytanya Ayyagari1:51 12 Dec '11  
GeneralMy vote of 2 Pinmembereuggg123456780:27 21 Jul '11  
GeneralGood Article !!!!!!! :-) PinmemberSuchitass1:02 11 May '11  
GeneralMy vote of 5 PinmemberMurat TARKUN7:51 7 Nov '10  
GeneralMicrosoft.VisualBasic.FileIO.FileSystem.CopyDirectory PinmemberVercas10:02 16 Oct '10  
Generalthanks for saving peoples time. PinmemberBehrooz_cs21:06 22 Apr '10  
Generalan easier way, non recursive Pinmemberkalvarez212:59 16 Dec '09  
GeneralRe: an easier way, non recursive Pinmemberdrweb8621:50 30 May '11  
GeneralPlease use C# PinmemberJasper4C#2:41 20 Jul '09  
GeneralRe: Please use C# PinmemberMember 128588612:49 20 Feb '11  
GeneralSmall fix PinmemberMember 404930522:50 14 Jul '08  
GeneralRe: Small fix Pinmemberchinese_zmm23:27 24 Mar '09  
GeneralMissing error handling PinmemberTzipi Levy0:44 30 Apr '08  
GeneralThank you Pinmemberubshreenath8:44 24 Sep '07  
GeneralOdd Things PinmemberSpencerja4:13 7 Sep '07  
GeneralExclude file PinmemberGC9N4:34 6 Jun '07  
GeneralThank you! Pinmemberkabbykray18:29 3 Jun '07  
GeneralSimpler one, based on string only Pinmembernantcom5:22 24 Dec '06  
Hey's it's not that complex! Just use getfiles and getdirectories
 

// using System.IO;
 
private void CopyFolder( string source, string dest )
{
if (!dest.EndsWith("\\")) dest += "\\";
 
foreach (string file in Directory.GetFiles( source ))
{
File.Copy(file, dest + Path.GetFileName(file), true);
}
 
foreach (string folder in Directory.GetDirectories( source ))
{
string subFolder = Path.GetFileName(folder);
Directory.CreateDirectory(dest + "\\" + subFolder);
CopyFolder(folder, dest + "\\" + subFolder);
}
}

GeneralRe: Simpler one, based on string only PinPopularmemberWernight22:55 8 Jul '08  
GeneralGood Article PinmemberKingTermite10:05 20 Jun '05  
GeneralRe: Good Article PinmemberGriffonRL21:10 20 Jun '05  
GeneralEnhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); Pinmemberli hai5:57 3 Feb '05  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); PinmemberGriffonRL21:11 20 Jun '05  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); PinmemberSteed Soft23:04 9 May '06  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); Pinmembertirumal123119:27 28 Dec '06  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 20 Nov 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid