Click here to Skip to main content
15,881,776 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
4.42/5 (49 votes)
19 Nov 20021 min read 406.5K   2.7K   61   55
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.

C#
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.

C#
// 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


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

Comments and Discussions

 
GeneralOdd Things Pin
Spencerja7-Sep-07 4:13
Spencerja7-Sep-07 4:13 
GeneralExclude file Pin
GC9N6-Jun-07 4:34
GC9N6-Jun-07 4:34 
GeneralThank you! Pin
kabbykray3-Jun-07 18:29
kabbykray3-Jun-07 18:29 
GeneralSimpler one, based on string only Pin
nantcom24-Dec-06 5:22
nantcom24-Dec-06 5:22 
GeneralRe: Simpler one, based on string only Pin
Wernight8-Jul-08 22:55
Wernight8-Jul-08 22:55 
GeneralGood Article Pin
KingTermite20-Jun-05 10:05
KingTermite20-Jun-05 10:05 
GeneralRe: Good Article Pin
GriffonRL20-Jun-05 21:10
GriffonRL20-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
li hai3-Feb-05 5:57 
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;

namespace Project1
{
public class Util
{
public Util()
{
}


///
/// Filesystem
///

public class FileSystem
{
// Copy directory structure recursively
public static void copyDirectory(string Src,string Dst, string[] SrcFilterPattern)
{

ArrayList FileCol = null;

if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar)
Dst+=Path.DirectorySeparatorChar;
if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);

FileCol = new ArrayList();

for (int i = 0; i < SrcFilterPattern.Length; i ++)
{
if (SrcFilterPattern[i].CompareTo("") == 0)
{
FileCol.AddRange(Directory.GetFileSystemEntries(Src));
}
FileCol.AddRange(Directory.GetFileSystemEntries(Src, SrcFilterPattern[i]));
}


foreach(string Element in FileCol)
{
// Sub directories
if(Directory.Exists(Element))
copyDirectory(Element,Dst+Path.GetFileName(Element), SrcFilterPattern);
// Files in directory
else
File.Copy(Element,Dst+Path.GetFileName(Element),true);
}


}


// Copy directory structure recursively
public static void copyDirectory(string sDir,string sDst, string fileFilterPattern)
{


try
{

Regex r = new Regex("(;|,)"); // Split on hyphens.
string[] fileFilters = r.Split(fileFilterPattern);
r = null;
copyDirectory(sDir, sDst, fileFilters);

}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}


// Copy directory structure recursively
public static void copyDirectory(string sDir,string sDst)
{
try
{
copyDirectory(sDir, sDst, "");
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}



static void Main(string[] args)
{
try
{
//copyDirectory(@"c:\temp",@"c:\temp\new", "*e.exe;*l.xml");
copyDirectory(@"c:\temp",@"c:\temp\new");
// Directory.Delete(@"c:\MySrcDirectory") to mimic a Directory.Move behaviour
}
catch(Exception Ex)
{
Console.Error.WriteLine(Ex.Message);
}
}
}


}
}
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
GriffonRL20-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
RubyPdf9-May-06 23:04
RubyPdf9-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
tirumal123128-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
RubyPdf28-Dec-06 21:16
RubyPdf28-Dec-06 21:16 
GeneralEnhance to get file filter, sample call Pin
li hai3-Feb-05 5:57
li hai3-Feb-05 5:57 
QuestionHow about mapped drives? Pin
OtC4-Aug-04 7:51
OtC4-Aug-04 7:51 
AnswerRe: How about mapped drives? Pin
ruionwriting23-Oct-08 6:41
ruionwriting23-Oct-08 6:41 
GeneralLittle help required ! Pin
vikas123423-Mar-04 3:30
vikas123423-Mar-04 3:30 
GeneralVB.NET Version Pin
starlogic8-Feb-04 13:56
starlogic8-Feb-04 13:56 
GeneralRe: VB.NET Version Pin
korcutt27-Apr-06 11:28
korcutt27-Apr-06 11:28 
QuestionHow to determine drive types Pin
Hing17-Nov-03 19:36
Hing17-Nov-03 19:36 
AnswerRe: How to determine drive types Pin
chinese_zmm24-Mar-09 23:18
chinese_zmm24-Mar-09 23:18 
AnswerRe: How to determine drive types Pin
FrozenHearted25-Mar-09 23:34
FrozenHearted25-Mar-09 23:34 
QuestionWhy this way? Pin
Mustafa Demirhan19-Nov-02 15:54
Mustafa Demirhan19-Nov-02 15:54 
AnswerRe: Why this way? Pin
GriffonRL19-Nov-02 21:35
GriffonRL19-Nov-02 21:35 
GeneralRe: Why this way? Pin
Mustafa Demirhan20-Nov-02 0:18
Mustafa Demirhan20-Nov-02 0:18 
GeneralRe: Why this way? Pin
GriffonRL20-Nov-02 1:24
GriffonRL20-Nov-02 1:24 

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

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