2011-08-22 40 views
41

¿Cómo puedo copiar todos los contenidos en un directorio a otro sin tener que recorrer cada archivo?Copie todos los archivos en el directorio

+0

vistazo aquí: http://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results y poner allí para el comando "copiar \ *. * YOURDIR " – fritzone

Respuesta

1

No puede. Pero puede utilizar algún tipo de código sucinto como Directory.GetFiles(mydir).ToList().ForEach(f => File.Copy(f, otherdir + "\\" f);

+3

Esto no funciona recursivamente. –

78

No puede. Ni Directory ni DirectoryInfo proporcionan un método Copy. Necesita implementar esto usted mismo.

void Copy(string sourceDir, string targetDir) 
{ 
    Directory.CreateDirectory(targetDir); 

    foreach(var file in Directory.GetFiles(sourceDir)) 
     File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file))); 

    foreach(var directory in Directory.GetDirectories(sourceDir)) 
     Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory))); 
} 

Lea los comentarios para tener en cuenta algunos problemas con este enfoque simplista.

+0

Esto solo copia archivos, no crea subdirectorios. Por lo tanto, si el destino aún no tiene la misma estructura de directorios, deberá agregar una línea al principio para crear el destino si aún no existe. – Ross

+1

@Ross: De hecho, corregido. Tenga en cuenta que esto no copia los atributos de seguridad, como los derechos de acceso. –

+1

con comprobar si los archivos y la carpeta existen funciona muy bien. if (! Directory.Exists (targetDir)) ... if (! File.Exists (file)) – Misi

0

Ejecutar xcopy source_directory\*.* destination_directory como un comando externo. Por supuesto, esto solo funcionará en máquinas con Windows.

+0

No debe usar las llamadas al sistema si no es necesario. Aquí, definitivamente no es necesario. –

+0

Es necesario dar que la pregunta indique ** sin buclear cada archivo **. – m0skit0

+0

¿Y qué crees que está haciendo xcopy? Simplemente no quería repetir, porque pensó que había una manera más fácil. No hay Y una llamada al sistema no es ni más fácil ni una buena forma en general. ¡Es fuertemente desaconsejado! –

8

Puede utilizar el método FileSystem.CopyDirectory de VB para simplificar la tarea:

using Microsoft.VisualBasic.FileIO; 

foo(){ 
    FileSystem.CopyDirectory(directoryPath, tempPath); 
} 
+2

Extraño a VB. Y la gente dice que puedes hacer todas las mismas cosas en C#. –

-1
Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"resources\html") 
    .ToList() 
    .ForEach(f => File.Copy(f, folder + "\\" + f.Substring(f.LastIndexOf("\\")))); 
2
using System.IO; 

string sourcePath = @"D:\test"; 
string targetPath = @"D:\test_new"; 
if (!Directory.Exists(targetPath)) 
{ 
    Directory.CreateDirectory(targetPath); 
} 
foreach (var srcPath in Directory.GetFiles(sourcePath)) 
{ 
    //Copy the file from sourcepath and place into mentioned target path, 
    //Overwrite the file if same file is exist in target path 
    File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true); 
} 
0

Esto funciona muy bien! Copiará directorios secundarios o puede simplemente volcar todos los archivos de todos los subdirectorios en una ubicación.

/// AUTHOR : Norm Petroff 
/// <summary> 
/// Takes the files from the PathFrom and copies them to the PathTo. 
/// </summary> 
/// <param name="pathFrom"></param> 
/// <param name="pathTo"></param> 
/// <param name="filesOnly">Copies all files from each directory to the "PathTo" and removes directory.</param> 
static void CopyFiles(String pathFrom, String pathTo, Boolean filesOnly) 
{ 
    foreach(String file in Directory.GetFiles(pathFrom)) 
    { 
     // Copy the current file to the new path. 
     File.Copy(file, Path.Combine(pathTo, Path.GetFileName(file)), true); 

     // Get all the directories in the current path. 
     foreach (String directory in Directory.GetDirectories(pathFrom)) 
     { 
      // If files only is true then recursively get all the files. They will be all put in the original "PathTo" location 
      // without the directories they were in. 
      if (filesOnly) 
      { 
       // Get the files from the current directory in the loop. 
       CopyFiles(directory, pathTo, filesOnly); 
      } 
      else 
      { 
       // Create a new path for the current directory in the new location.      
       var newDirectory = Path.Combine(pathTo, new DirectoryInfo(directory).Name); 

       // Copy the directory over to the new path location if it does not already exist. 
       if (!Directory.Exists(newDirectory)) 
       { 
        Directory.CreateDirectory(newDirectory); 
       } 

       // Call this routine again with the new path. 
       CopyFiles(directory, newDirectory, filesOnly); 
      } 
     } 
    } 
} 
Cuestiones relacionadas