2012-02-09 26 views
6

Tengo algún problema con la copia del archivo de un directorio a otro creando la carpeta si esa carpeta no existe en el directorio directorio de destino.Cómo copiar un archivo de un directorio a otro creando la carpeta si esa carpeta no existe

Ejemplo:

  • ruta Fuente: C:\temp\test\1.txt
  • Ruta de destino: C:\Data\

Si C:\Data\ no contiene "temp" o la carpeta "prueba", se debe crear la carpeta antes afrontamiento 1.txt.

copiado a C:\Data\temp\test\1.txt

A continuación es mi código. Pero no funciona ..

Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click 
      Dim sourcepath As String = "C:\temp\test\1.txt" 
    Dim DestPath As String = "C:\Data\" 
    CopyDirectory(sourcepath, DestPath) 
End Sub 

Private Shared Sub CopyDirectory(sourcePath As String, destPath As String) 
    If Not Directory.Exists(destPath) Then 
     Directory.CreateDirectory(destPath) 
    End If 

    For Each file__1 As String In Directory.GetFiles(sourcePath) 
     Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1)) 
     File.Copy(file__1, dest) 
    Next 

    For Each folder As String In Directory.GetDirectories(sourcePath) 
     Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder)) 
     CopyDirectory(folder, dest) 
    Next 
End Sub 
+0

Cualquier error? y está usando XP o Windows 7 –

+4

Frases como "no funciona" deben ser bloqueadas por SO al enviar una pregunta;) –

Respuesta

9

El siguiente no es un directorio.

Dim sourcepath As String = "C:\temp\test\1.txt" 

porque está utilizando como un directorio en el Directory.GetFiles(sourcePath).

Aparte de eso, recomiendo elaborar sus preguntas más la próxima vez. El código plantea excepciones significativas como DirectoryNotFoundException con la ruta adecuada como mensaje o (si el archivo existe) un IOException con el mensaje "El nombre del directorio no es válido". Deberías haber agregado eso a la pregunta.

Así que la solución es simplemente para eliminar el 1.txt desde el directorio de nombres:

Dim sourcepath As String = "C:\temp\test\" 

Si necesita copiar sólo un archivo, utilice CopyTo method:

Dim sourcepath As String = "C:\temp\test\" 
Dim DestPath As String = "C:\temp\Data\" 
If Not Directory.Exists(DestPath) Then 
    Directory.CreateDirectory(DestPath) 
End If 
Dim file = New FileInfo("C:\temp\test\1.txt") 
file.CopyTo(Path.Combine(DestPath, file.Name), True) 
+0

Tengo un montón de archivos de texto pero solo quiero copiar el archivo 1.txt. – user1101157

+0

@ user1101157: actualicé mi respuesta. –

0
Dim strMasterResourceDirectory As String 
    Dim strDirectory As String 

    strDirectory = "C:\TestDestination" 
    strMasterResourceDirectory = "TestResource" 

    If My.Computer.FileSystem.DirectoryExists(strDirectory) = False Then 
     My.Computer.FileSystem.CreateDirectory(strDirectory) 
    End If 

    ' Loop through each file in the directory 
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strDirectory).GetFiles 

     If file.Name <> "Thumbs.db" Then 

      System.IO.File.Delete(strDirectory & "\" & file.Name) 

     End If 
    Next 

    ' Loop through each file in the directory 
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strMasterResourceDirectory).GetFiles 

     If file.Name <> "Thumbs.db" Then 

      ' copy resource to users local directory 

      file.CopyTo(strDirectory & "\" & file.Name) 

     End If 
    Next 
+0

¡Bienvenido a StackOverflow! Considere agregar una pequeña explicación a su código. ¡Gracias! – Aurasphere

Cuestiones relacionadas