Copy entire directory

S

shapper

Hello,

How can I copy an entire directory with all its sub folders and files
to another location?

Thanks,

Miguel
 
A

Arne Vajhøj

How can I copy an entire directory with all its sub folders and files
to another location?

I wrote this many years ago:

private void XCopy(string dir1, string dir2)
{
string[] files = Directory.GetFiles(dir1);
foreach (string f in files) {
File.Copy(f, dir2 + f.Substring(dir1.Length), true);
}
string[] dirs = Directory.GetDirectories(dir1);
foreach (string d in dirs) {
XCopy(d, dir2 + d.Substring(dir1.Length));
}
}

I don't think newer .NET versions provide anything better.

You may need to change the code to create the to
directories - I think my example were for a case
where the directory structure already existed for to.

Arne
 
D

David Boucherie & Co

using System;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args )
{
// Copies the content of the source directory to a target
// directory.
// You can change the implementation to actually copy the
// whole SourceDir (including SourceDir itself), but
// here only the content is copied.
//
// Also, you will probably want some more checking
// to make copy safe.
// Do you want to overwrite files?
// Do you want to allow a copy from source to source?
// ...

CopyDir( @"C:\Temp\SourceDir", @"C:\Temp\TargetDir" );

Console.ReadLine();
}

public static void CopyDir( string source, string target )
{
Console.WriteLine(
"\nCopying Directory:\n \"{0}\"\n-> \"{1}\"",
source, target );

if ( !Directory.Exists( target ) )
Directory.CreateDirectory( target );
string[] sysEntries =
Directory.GetFileSystemEntries( source );

foreach ( string sysEntry in sysEntries )
{
string fileName = Path.GetFileName( sysEntry );
string targetPath = Path.Combine( target, fileName );
if ( Directory.Exists( sysEntry ) )
CopyDir( sysEntry, targetPath );
else
{
Console.WriteLine( "\tCopying \"{0}\"", fileName );
File.Copy( sysEntry, targetPath, true );
}
}
}
}
}
 

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

Similar Threads

Get Parent Directory 15
Delete all files 7
Get Mime Type of File 4
Linq > Contains 2
copy directory 14
Build Script? 3
Combine Files 2
directory copy 4

Top