Monday, July 25, 2011

C# code to Copy Directory from source to destination

public static void CopyDirectory(string sourcePath, string destinationPath, bool recurse)

// The calling function will need to handle the error if sourcePath cannot be found at runtime

{

String[] files;

if (destinationPath[destinationPath.Length-1] != Path.DirectorySeparatorChar)

destinationPath+=Path.DirectorySeparatorChar;

if(!Directory.Exists(destinationPath)) Directory.CreateDirectory(destinationPath);

files = Directory.GetFileSystemEntries (sourcePath);

foreach(string element in files)

{

if (recurse)

{

// copy sub directories (recursively)

if(Directory.Exists(element))

CopyDirectory(element,destinationPath+Path.GetFileName(element), recurse);

// copy files in directory

else

File.Copy(element,destinationPath+Path.GetFileName(element),true);

}

else

{

// only copy files in directory

if(!Directory.Exists(element))

File.Copy(element,destinationPath+Path.GetFileName(element),true);

}

}

}


No comments:

Post a Comment