Thursday, September 18, 2008

Recursive copy of Files and Folders with VB.Net

It seems so banal, but sometimes the copy of files and folders conteined into a folder can undermine a developer, maybe for its banality.
For this reason, here you have an example of recoursive copy of files and folders.

Private Sub Copy(ByVal SourcePath As String, _
            ByVal DestinationPath As String)
    Dim Files() As String

    If DestinationPath.Chars(DestinationPath.Length - 1) <>
            Path.DirectorySeparatorChar Then
        DestinationPath += Path.DirectorySeparatorChar
    End If

    If Not Directory.Exists(DestinationPath) Then
    End If

    Files = Directory.GetFileSystemEntries(SourcePath)

    Dim Element As String

    For Each Element In Files
        'Sub folders
        If Directory.Exists(Element) Then
            Copy(Element, DestinationPath +
            ' File in folder
            File.Copy(Element, DestinationPath +
                Path.GetFileName(Element), True)
        End If
    Next Element
End Sub

No comments: