Copying Directory / Subdirectory and Files

  • Thread starter Thread starter Amos Soma
  • Start date Start date
A

Amos Soma

Does anyone know the easiest way, in C#, to copy all directories and files
starting with some root directory? For example, how might I copy all files
and directories starting with 'C:\Program Files\' to some destination
directory.

Thanks.
 
Look at the System.IO namespace.

Using the DirectoryInfo object, you can iterate through its files and
subdirectories and copy each file using the CopyTo method.
 
Thanks Ben. I know I can do that. I was hoping this wasn't the 'easiest' way
to do it.
 
Hi Amos

If you are willing to use interop the FileSystemObject offers a CopyFolder
method...

HTH

Nigel Armstrong
 
Amos Soma said:
Thanks Ben. I know I can do that. I was hoping this wasn't the 'easiest'
way
to do it.

There is an easier way, use System.Management classes and WMI's
Win32_Directory class .

Following is a sample:

using System.Management;
.....

string dirName = @"c:\\source"; // beware the double quotes!
string objPath = "Win32_Directory.Name=" + "\"" + dirName + "\"";

using (ManagementObject dir= new ManagementObject(objPath))
{
ManagementBaseObject inputArgs = dir.GetMethodParameters("CopyEx");
inputArgs["FileName"] = "C:\\destination";
inputArgs["Recursive"] = true; // Recurse folder and subfolders
ManagementBaseObject outParams = dir.InvokeMethod("CopyEx", inputArgs,
null);
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Success");
else Console.WriteLine("Failed with error code: {0}", ret);
}

Willy.
 
Back
Top