Click here to Skip to main content
6,306,412 members and growing! (17,670 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » File System     Intermediate

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

By GriffonRL

Simple C#/.NET tip to copy an entire directory tree to another directory
C#, Windows, .NET 1.0, Visual Studio, Dev
Posted:18 Nov 2002
Updated:19 Nov 2002
Views:171,922
Bookmarked:42 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
41 votes for this article.
Popularity: 6.55 Rating: 4.06 out of 5
1 vote, 2.6%
1

2
4 votes, 10.3%
3
13 votes, 33.3%
4
21 votes, 53.8%
5

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


Member
Richard Lopes
Programmer from Paris, France.

I worked in France, the US, New Caledonia and now in New Zealand.

I welcome any business opportunity anywhere and in New Zealand.

My blog: http://sili.co.nz/blog
My twitter: http://www.twitter.com/richard_lopes
Occupation: Software Developer (Senior)
Company: Sellla Ltd
Location: New Zealand New Zealand

Other popular Files and Folders articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
GeneralSmall fix PinmemberMember 404930523:50 14 Jul '08  
GeneralRe: Small fix Pinmemberchinese_zmm0:27 25 Mar '09  
GeneralMissing error handling PinmemberTzipi Levy1:44 30 Apr '08  
GeneralThank you Pinmemberubshreenath9:44 24 Sep '07  
GeneralOdd Things PinmemberSpencerja5:13 7 Sep '07  
GeneralExclude file PinmemberGC9N5:34 6 Jun '07  
GeneralThank you! Pinmemberkabbykray19:29 3 Jun '07  
GeneralSimpler one, based on string only Pinmembernantcom6:22 24 Dec '06  
GeneralRe: Simpler one, based on string only PinmemberWernight23:55 8 Jul '08  
GeneralGood Article PinmemberKingTermite11:05 20 Jun '05  
GeneralRe: Good Article PinmemberGriffonRL22:10 20 Jun '05  
GeneralEnhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); Pinmemberli hai6:57 3 Feb '05  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); PinmemberGriffonRL22:11 20 Jun '05  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); PinmemberSteed Soft0:04 10 May '06  
GeneralRe: Enhance to get file filter, sample call //copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml"); Pinmembertirumal123120:27 28 Dec '06  
AnswerRe: Enhance to get file filter, sample call //copyDirectory(@&amp;quot;c:\temp&amp;quot;,@&amp;quot;c:\temp\new&amp;quot;, &amp;quot;*e.exe;*l.xml&amp;quot;); PinmemberSteed Soft22:16 28 Dec '06  
GeneralEnhance to get file filter, sample call Pinmemberli hai6:57 3 Feb '05  
GeneralHow about mapped drives? Pinsussotc8:51 4 Aug '04  
GeneralRe: How about mapped drives? Pinmemberbass4g0d7:41 23 Oct '08  
GeneralLittle help required ! Pinsussvikas12344:30 23 Mar '04  
GeneralVB.NET Version Pinmemberstarlogic14:56 8 Feb '04  
GeneralRe: VB.NET Version Pinmemberkorcutt12:28 27 Apr '06  
GeneralHow to determine drive types Pinmemberliuhoihing20:36 17 Nov '03  
GeneralRe: How to determine drive types Pinmemberchinese_zmm0:18 25 Mar '09  
GeneralRe: How to determine drive types PinmemberFrozenHearted0:34 26 Mar '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Nov 2002
Editor: Nishant Sivakumar
Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project