Click here to Skip to main content
Click here to Skip to main content
Go to top

Copy Directory Recursively using WMI

, 22 Sep 2007
Rate this:
Please Sign up or sign in to vote.
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.

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

Share

About the Author

nitstheone

India India
No Biography provided

Comments and Discussions

 
GeneralSHFileOperation PinmemberStephen Hewitt23-Aug-06 13:57 
GeneralRe: SHFileOperation Pinmembernitstheone25-Aug-06 5:07 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 23 Sep 2007
Article Copyright 2006 by nitstheone
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid