Introduction
.NET or Win32 does not support copying of directories, and copying them by enumerating through all files and directories is stupid. Fortunately WMI does have the functionality to copy directories recursively.
The Code
static uint DirectoryCopy(string SourcePath, string DestinationPath, bool Recursive)
{
string objPath = @"\\.\root\cimv2:Win32_Directory.Name="+
"\""+SourcePath.Replace("\\","\\\\")+"\"";
using (ManagementObject dir = new ManagementObject(objPath))
{
ManagementBaseObject inputArgs = dir.GetMethodParameters("CopyEx");
inputArgs["FileName"] = DestinationPath.Replace("\\", "\\\\");
inputArgs["Recursive"] = Recursive;
ManagementBaseObject outParams = dir.InvokeMethod("CopyEx", inputArgs, null);
return ((uint)(outParams.Properties["ReturnValue"].Value));
}
}
If destination directory is already present then we get error, so I have deleted it.
Currently the code assumes that the source path is on the local machine, but you can modify it to include source machine name by replacing \\.\ with \\<Machine name>\ in string objPath.
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