Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C#

Copy Directory Recursively using WMI

Rate me:
Please Sign up or sign in to vote.
3.67/5 (5 votes)
22 Sep 2007 48.1K   24   2
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

C#
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.

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSHFileOperation Pin
Stephen Hewitt23-Aug-06 13:57
Stephen Hewitt23-Aug-06 13:57 
GeneralRe: SHFileOperation Pin
nitstheone25-Aug-06 5:07
nitstheone25-Aug-06 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.