Copying directories?

S

Seth

Is there an easy way to copy a directory and its subdirectory structure with
all the files. I've not found a method that can do this and seems like I'm
gonna have to implement a recurssive function that manually copies each file
and creates directories as needed. Anyone got any easier or better ideas?
TIA
 
M

Morten Wennevik

Hi Seth,

Directory.Move(sourceDir, destDir); ?
"Moves a file or a directory and its contents to a new location."

Happy coding!
Morten
 
M

Morten Wennevik

My bad, I was a bit hasty there.

No, I don't think there are any copy methods.
 
S

Seth

Had to write my own method for it. Here is it incase someone else needs it:

private void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
// Create destination directory
Directory.CreateDirectory(destination.FullName);

// Copy files in route
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
File.Copy(file.FullName, destination.FullName + @"\" + file.Name);
}
// Copy files in sub folders
DirectoryInfo[] directories = source.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
DirectoryInfo dest = new DirectoryInfo(destination.FullName + @"\" +
directory.Name);
CopyDirectory(directory, dest);
}
}

and you call it with something like this:

DirectoryInfo source = new DirectoryInfo(@"c:\temp");
DirectoryInfo destination = new DirectoryInfo(@"c:\temp2");
CopyDirectory(source, destination);


Hope that helps someone or at least saves them some time.
 

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