From: shapper on 26 Jun 2010 20:58 Hello, How can I copy an entire directory with all its sub folders and files to another location? Thanks, Miguel
From: Arne Vajhøj on 26 Jun 2010 21:10 On 26-06-2010 20:58, shapper wrote: > 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
From: David Boucherie & Co on 26 Jun 2010 22:11 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 ); } } } } }
|
Pages: 1 Prev: C#.net custom control Next: Chossing port for server lsitening |