Copying Directory / Subdirectory and Files

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.
 
B

Ben Lucas

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.
 
A

Amos Soma

Thanks Ben. I know I can do that. I was hoping this wasn't the 'easiest' way
to do it.
 
G

Guest

Hi Amos

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

HTH

Nigel Armstrong
 
W

Willy Denoyette [MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top