howto recursively copy a folder ?

  • Thread starter Thread starter Antonio Lopez Arredondo
  • Start date Start date
A

Antonio Lopez Arredondo

hi all !!!

I need to copy a folder and its subfolders to another location; which class
should I use ?

could only find the System.IO.Directory.MOVE but don't know how to COPY.

thanks in advance,
ant
 
It does not really exists a class that does this out of the box in .NET (as
far as I know ;-) )
However, here is a sample:

You should replace the BTException class (my custom exception class by
yours...)
José



//--------------------------------------------------------------------------
---------------
/// <summary>
/// This method will make a copy of a directory (recursive).
/// If a file alreay exists, it will be overwritten.
/// </summary>
/// <param name="strSrcdir">Directory to copy (eg: C:\myDirectory)</param>
/// <param name="strDestDir">Where to copy the directory
(D:\myNewDirectory). </param>
public static void CopyDirectory(string sourceDirectoryName, string
targetDirectoryName)
{
try
{
// Create directory if needed
Directory.CreateDirectory(targetDirectoryName);

// Treate all the file under current source directory
string[] files = Directory.GetFiles(sourceDirectoryName);
foreach(string fileName in files)
File.Copy(fileName, targetDirectoryName +
Path.DirectorySeparatorChar +
Path.GetFileName(fileName),true);

// now treat all subdirectory and their related files (called this
routine recursively)
string[] directories = Directory.GetDirectories(sourceDirectoryName);
foreach(string directory in directories)
CopyDirectory(directory, targetDirectoryName +
Path.DirectorySeparatorChar +
Path.GetFileName(directory));
}
catch (BTException ex0)
{
// This is an exception thrown while recursively be called. Just throw
further
throw ex0;
}
catch (Exception ex)
{
throw new BTException("Unable to Copy Directory " + sourceDirectoryName
+
" to " + targetDirectoryName + ". Check Path/File names. Err:
" + ex.Message,
Status.Stat.ECannotWriteFile, Severity.Level.Error);
}
}
 
Back
Top