2010-04-30 22 views
7

Necesito copiar una carpeta de una unidad a un disco duro extraíble. La carpeta que necesita copiarse tendrá muchas subcarpetas y archivos. La entrada será Ruta de origen y Ruta de destino.Cuál es la mejor manera de copiar una carpeta y todas las subcarpetas y archivos usando C#

como ..

Fuente Path: "C: \ SourceFolder"

ruta de destino: "E: \"

Después de la copia se realiza, i shud ser capaz de ver la carpeta " SourceFolder "en mi E: unidad.

Gracias.

+1

Este es un duplicado, ver : http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c – Ash

+0

Otro dup licate: http://stackoverflow.com/questions/627504/what-is-the-best-way-to-recursively-copy-contents-in-c – Ash

+0

Hm, bueno ahora la gente está copiando de las otras preguntas, por lo que Voy a votar para cerrar. –

Respuesta

2
private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting) 
     { 
      bool ret = true; 
      try 
      { 
       SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; 
       DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; 

       if (Directory.Exists(SourcePath)) 
       { 
        if (Directory.Exists(DestinationPath) == false) 
         Directory.CreateDirectory(DestinationPath); 

        foreach (string fls in Directory.GetFiles(SourcePath)) 
        { 
         FileInfo flinfo = new FileInfo(fls); 
         flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); 
        } 
        foreach (string drs in Directory.GetDirectories(SourcePath)) 
        { 
         DirectoryInfo drinfo = new DirectoryInfo(drs); 
         if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false) 
          ret = false; 
        } 
        Directory.CreateDirectory(DI_Target + "//Database"); 
       } 
       else 
       { 
        ret = false; 
       } 
      } 
      catch (Exception ex) 
      { 
       ret = false; 
      } 
      return ret; 
     } 
+0

qué Directorio.CreateDirectory (DI_Target + "// Base de datos"); es –

3

Cómo: Copiar, Eliminar y mover archivos y carpetas (Guía de programación de C#)
http://msdn.microsoft.com/en-us/library/cc148994.aspx

Cómo iterar a través de un árbol de directorios (Guía de programación de C#)
http://msdn.microsoft.com/en-us/library/bb513869.aspx

+0

Solo fyi, el código en esa página deja fuera la parte que realmente necesita. Tenga en cuenta el comentario, * Para iterar recursivamente a través de todas las subcarpetas en el directorio actual, consulte "Cómo: Ir a través de un árbol de directorios". * – egrunin

+0

@egrunin: Gracias. –

8

Encontrado esto en Channel9. No lo he probado yo mismo.

public static class DirectoryInfoExtensions 
{ 
    // Copies all files from one directory to another. 
    public static void CopyTo(this DirectoryInfo source, 
      string destDirectory, bool recursive) 
    { 
     if (source == null) 
      throw new ArgumentNullException("source"); 
     if (destDirectory == null) 
      throw new ArgumentNullException("destDirectory"); 
     // If the source doesn't exist, we have to throw an exception. 
     if (!source.Exists) 
      throw new DirectoryNotFoundException(
        "Source directory not found: " + source.FullName); 
     // Compile the target. 
     DirectoryInfo target = new DirectoryInfo(destDirectory); 
     // If the target doesn't exist, we create it. 
     if (!target.Exists) 
      target.Create(); 
     // Get all files and copy them over. 
     foreach (FileInfo file in source.GetFiles()) 
     { 
      file.CopyTo(Path.Combine(target.FullName, file.Name), true); 
     } 
     // Return if no recursive call is required. 
     if (!recursive) 
      return; 
     // Do the same for all sub directories. 
     foreach (DirectoryInfo directory in source.GetDirectories()) 
     { 
      CopyTo(directory, 
       Path.Combine(target.FullName, directory.Name), recursive); 
     } 
    } 
} 

y el uso se ve así:

var source = new DirectoryInfo(@"C:\users\chris\desktop"); 
source.CopyTo(@"C:\users\chris\desktop_backup", true); 
+0

+1 Bonito método de extensión. –

-1

¿Por qué no usar algo como Robocopy?

Tiene una opción de duplicación donde la estructura de directorio de origen se copia como está en el destino. Hay varias opciones de línea de comando. Puede ahorrarte el esfuerzo de replicar las funciones de tu código.

+1

Porque RoboCopy es una aplicación externa. Siempre es mejor intentar hacer cosas de forma nativa en el código primero (si no es demasiado complicado hacerlo), antes de recurrir al bombardeo a otro programa para hacerlas. –

11

Creo que esto es todo.

public static void CopyFolder(DirectoryInfo source, DirectoryInfo target) { 
    foreach (DirectoryInfo dir in source.GetDirectories()) 
     CopyFolder(dir, target.CreateSubdirectory(dir.Name)); 
    foreach (FileInfo file in source.GetFiles()) 
     file.CopyTo(Path.Combine(target.FullName, file.Name)); 
} 
+0

Tiene un problema de permiso. ¿Puedes superarlo? –

-1

Y aquí es una opinión diferente sobre el problema:

System.Diagnostics.ProcessStartInfo psi = 
    new System.Diagnostics.ProcessStartInfo(@"XCOPY C:\folder D:\Backup\folder /i"); 
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
psi.UseShellExecute = false; 
System.Diagnostics.Process copyFolders = System.Diagnostics.Process.Start(psi); 
copyFolders.WaitForExit(); 
1

para los empleados de Google: en Win32 puro/C++, utilice SHCreateDirectoryEx

inline void EnsureDirExists(const std::wstring& fullDirPath) 
{ 
    HWND hwnd = NULL; 
    const SECURITY_ATTRIBUTES *psa = NULL; 
    int retval = SHCreateDirectoryEx(hwnd, fullDirPath.c_str(), psa); 
    if (retval == ERROR_SUCCESS || retval == ERROR_FILE_EXISTS || retval == ERROR_ALREADY_EXISTS) 
     return; //success 

    throw boost::str(boost::wformat(L"Error accessing directory path: %1%; win32 error code: %2%") 
     % fullDirPath 
     % boost::lexical_cast<std::wstring>(retval)); 

    //TODO *djg* must do error handling here, this can fail for permissions and that sort of thing 
} 
+1

¿No era esta la pregunta sobre C#? No es que me esté quejando (sigue votando). Método muy útil, pero un poco fuera de contexto aquí –

Cuestiones relacionadas