Copy Directory or Move folder in .NET

By Default, .NET doesn't provide any inbuilt method to copy directory/sub-directory or move folder as like XCopy command in DOS. Here is the method for this:

private void XCopy(String src, String dest,Boolean isOverwrite)
{
DirectoryInfo currentDirectory;
currentDirectory = new DirectoryInfo(src);
if (!Directory.Exists(dest))
Directory.CreateDirectory(dest);
foreach (FileInfo filein in currentDirectory.GetFiles())
{
filein.CopyTo(System.IO.Path.Combine(dest, filein.Name), true);
// To move files uncomment following line
// filein.Delete();
}
foreach (DirectoryInfo dr in currentDirectory.GetDirectories())
{
XCopy(dr.FullName, Path.Combine(dest, dr.Name), isOverwrite);
}
}

No comments:

Post a Comment