Question 35

Comment copier, déplacer, supprimer ou renommer une arborescence complète de dossiers ?

Il faut employer l'API SHFileOperation(). L'exemple suivant effectue une opération de copie. Si vous désirez déplacer, supprimer ou renommer une arborescence de dossiers, il vous suffit de remplacer le membre .wFunc de la structure par FO_MOVE, FO_DELETE ou FO_RENAME.

Private Type SHFILEOPSTRUCT
    hWnd As Long
    wFunc As Long
    pFrom As String
    pTo As String
    fFlags As Integer
    fAnyOperationsAborted As Long
    hNameMappings As Long
    lpszProgressTitle As String 'Only used if FOF_SIMPLEPROGRESS
End Type

Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

Private Const FO_COPY = &H2
Private Const FO_DELETE = &H3
Private Const FO_MOVE = &H1
Private Const FO_RENAME = &H4
Private Const FOF_ALLOWUNDO = &H40
Private Const FOF_CONFIRMMOUSE = &H2
Private Const FOF_FILESONLY = &H80
Private Const FOF_MULTIDESTFILES = &H1
Private Const FOF_NOCONFIRMATION = &H10
Private Const FOF_NOCONFIRMMKDIR = &H200
Private Const FOF_RENAMEONCOLLISION = &H8
Private Const FOF_SILENT = &H4
Private Const FOF_SIMPLEPROGRESS = &H100
Private Const FOF_WANTMAPPINGHANDLE = &H20

Private Sub Form_Click()
    ' Copie du répertoire "C:\Tmp" et "C:\I386" vers "C:\Tmp2"
    ' à l'aide de l'SHFileOperation()
    Dim RC As Long
    Dim FileOper As SHFILEOPSTRUCT

    With FileOper
        .hWnd = Me.hWnd
        .wFunc = FO_COPY
        .pFrom = "C:\Tmp" & vbNullChar & "C:\I386" & vbNullChar & vbNullChar
        .pTo = "C:\Tmp2" & vbNullChar & vbNullChar
        .fFlags = FOF_SIMPLEPROGRESS Or FOF_ALLOWUNDO
    End With

    RC = SHFileOperation(FileOper)

    If RC <> 0 Then
        MsgBox "Erreur API SHFileOperation()", vbExclamation
    End If

End Sub

Date de publication : 07 juillet 2002
Dernière modification : 07 juillet 2002
Rubriques : Fichiers & dossiers
Mots-clés : dossiers, copier, déplacer, renommer, supprimer, arborescence, récursivement