65.9K
CodeProject is changing. Read more.
Home

Copy Directory Recursively using WMI

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (5 votes)

Aug 22, 2006

viewsIcon

48335

This article tells how to copy a directory recursively using WMI

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) 
{ 
  //if (Directory.Exists(DestinationPath)) 
  //  Directory.Delete(DestinationPath, true); 
  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.