2009-03-09 13 views

risposta

34

Ebbene si può provare questo

DirectoryInfo sourcedinfo = new DirectoryInfo(@"E:\source"); 
DirectoryInfo destinfo = new DirectoryInfo(@"E:\destination"); 
copy.CopyAll(sourcedinfo, destinfo); 

e questo è il metodo che fare tutto il lavoro:

public void CopyAll(DirectoryInfo source, DirectoryInfo target) 
{ 
    try 
    { 
     //check if the target directory exists 
     if (Directory.Exists(target.FullName) == false) 
     { 
      Directory.CreateDirectory(target.FullName); 
     } 

     //copy all the files into the new directory 

     foreach (FileInfo fi in source.GetFiles()) 
     { 
      fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); 
     } 


     //copy all the sub directories using recursion 

     foreach (DirectoryInfo diSourceDir in source.GetDirectories()) 
     { 
      DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name); 
      CopyAll(diSourceDir, nextTargetDir); 
     } 
     //success here 
    } 
    catch (IOException ie) 
    { 
     //handle it here 
    } 
} 

Spero che questo vi aiuterà :)

+3

Grande codice ce n'è uno cosa cambierei: // controlla se la directory di destinazione esiste if (Directory.Exists (target.FullName) == false) { Directory.CreateDirectory (targ et.FullName); } si può solo l'oggetto DirectoryInfo che si ha già: if (! Target.Exists) { target.Create(); } – greektreat

+0

ha funzionato bene per me senza modifiche. –

+1

un paio di volte ho avuto 'target.Exists' non funziona correttamente dove' Directory.Exists (target.FullName) 'ha ... –

18

Basta usare Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory in Microsoft.VisualBasic.dll montaggio.

Aggiungere un riferimento alla Microsoft.VisualBasic

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination); 
+4

sembra utile. come mai quella classe Directory non ha questo metodo ?? –

6

È possibile utilizzare SearchOption.AllDirectories per cercare ricorsivamente giù cartelle, è sufficiente creare le directory prima di copiare ...

// string source, destination; - folder paths 
int pathLen = source.Length + 1; 

foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories)) 
{ 
    string subPath = dirPath.Substring(pathLen); 
    string newpath = Path.Combine(destination, subPath); 
    Directory.CreateDirectory(newpath); 
} 

foreach (string filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories)) 
{ 
    string subPath = filePath.Substring(pathLen); 
    string newpath = Path.Combine(destination, subPath); 
    File.Copy(filePath, newpath); 
} 
+1

geniale! l'unica cosa che ho dovuto fare è int pathLen = source.Length + 1 – nabeelfarid

+0

Cheers, tweak made :-) – Keith

Problemi correlati