Les Snippets

Connexion

Copier un dossier et tout son contenu

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 20/04/2006 16:17:55 et initié par MorpionMx [Liste]
Date de mise à jour : 14/06/2008 17:47:30
Vue : 15068
Catégorie(s) : Fichier / Disque
Langages dispo pour ce code :
- C# 1.x, C# 2.x
- Javascript
- Windev
- VB 2005, VB.NET 1.x
- VB 2005, VB.NET 1.x
- VB6, VBA



Langage : C# 1.x , C# 2.x
Date ajout : 20/04/2006
Posté par MorpionMx [Liste]
DateMAJ : 03/06/2006
//using System.IO;

public static void CopyDir(string sourceDir, string destDir) 
{
    DirectoryInfo dir = new DirectoryInfo(sourceDir);    if (dir.Exists) 
    {
        string realDestDir;
        if (dir.Root.Name != dir.Name) 
       {
           realDestDir = Path.Combine(destDir, dir.Name); 
           if (!Directory.Exists(realDestDir))
               Directory.CreateDirectory(realDestDir); 
       }
       else realDestDir = destDir;       
       foreach (string d in Directory.GetDirectories(sourceDir)) 
           CopyDir(d, realDestDir);
       foreach (string file in Directory.GetFiles(sourceDir)) 
       {

            string fileNameDest = Path.Combine(realDestDir, Path.GetFileName(file)); 
            //if (!File.Exists(fileNameDest))

            File.Copy(file, fileNameDest, true); 
       }
    }
}

Langage : Javascript
Date ajout : 21/04/2006
Posté par bultez [Liste]

function CopyDir(sourceDir,destDir,ecraser)
{
 var tmp = ecraser ? ecraser : false;
 var fso=new ActiveXObject("Scripting.FileSystemObject")
 fso.CopyFolder(sourceDir,destDir,tmp);
}
/*
le 3ème paramètre autorise ou non ( par défaut )
l'écrasement des fichiers déjà existants dans le
répertoire de destination.
*/
Remarque :
ne fonctionne qu'avec Windows + Internet Explorer.
Langage : Windev
Date ajout : 15/06/2006
Posté par Elian Lacroix [Liste]
fRepCopie(<RepertoireSource>, <RepertoireDestination>, frRécursif)
Langage : VB.NET 1.x , VB 2005
Date ajout : 15/11/2006
Posté par Drikce06 [Liste]
Dim UIOption As Microsoft.VisualBasic.FileIO.UIOption 
Private Sub CopieRepertoire(ByVal RepertoireSource As String, ByVal RepertoireDestination As String)
If My.Computer.FileSystem.DirectoryExists(RepertoireSource) Then


'si le répertoire de destination n'existe pas, celui-ci est créé

'voir l'aide pour plus de détails sur les options (progression, remplacer si fichier existe déjà ...)
My.Computer.FileSystem.CopyDirectory(RepertoireSource, RepertoireDestination, UIOption.OnlyErrorDialogs, FileIO.UICancelOption.ThrowException) 
Else
MsgBox("Le répertoire source n'existe pas") 
End If

End Sub

'Exemple d'utilisation
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
CopieRepertoire("C:\test", "C:\test2")
End Sub


Langage : VB.NET 1.x , VB 2005
Date ajout : 22/01/2007
Posté par Charles Racaud [Liste]
Private Sub CopyDirectory(ByVal sourceDirName As StringByVal destDirName As StringOptional ByVal overwrite As Boolean = False)
  If Not String.Equals(sourceDirName, destDirName) And System.IO.Directory.Exists(sourceDirName) Then
    If Not System.IO.Directory.Exists(destDirName) Then System.IO.Directory.CreateDirectory(destDirName)
    For Each Directory As System.IO.DirectoryInfo In New System.IO.DirectoryInfo(sourceDirName).GetDirectories()
      Call CopyDirectory(Directory.FullName, System.IO.Path.Combine(destDirName, Directory.Name), overwrite)
    Next
    For Each File As System.IO.FileInfo In New System.IO.DirectoryInfo(sourceDirName).GetFiles()
      If Not System.IO.File.Exists(System.IO.Path.Combine(destDirName, File.Name)) OrElse overwrite Then
        System.IO.File.Copy(File.FullName, System.IO.Path.Combine(destDirName, File.Name), overwrite)
      End If
    Next
  End If
End Sub
Langage : VB6 , VBA
Date ajout : 11/06/2008
Posté par PCPT [Liste]
DateMAJ : 14/06/2008
Private Const NOERROR As Long 0&
Private Const FO_COPY As Long &H2
Private Const FOF_ALLOWUNDO As Long &H40
Private Const FOF_CONFIRMMOUSE As Long &H2
Private Const FOF_FILESONLY As Long &H80 '  on *.*, do only files
Private Const FOF_MULTIDESTFILES As Long = &H1
Private Const FOF_NOCONFIRMATION As Long = &H10 '  Don't prompt the user.
Private Const FOF_NOCONFIRMMKDIR As Long = &H200 ' don't confirm making any needed dirs
Private Const FOF_RENAMEONCOLLISION As Long  = &H8
Private Const FOF_SILENT As Long &H4    ' don't create  progress/report
Private Const FOF_SIMPLEPROGRESS As Long = &H100 ' means don't show names of files
Private Const FOF_WANTMAPPINGHANDLE As Long  = &H20 ' Fill in SHFILEOPSTRUCT.hNameMappings
Private Type SHFILEOPSTRUCT
    hWnd As Long
    wFunc As Long
    pFrom As String
    pTo As String
    fFlags As Integer
    fAborted As Boolean
    hNameMaps As Long
    sProgress As String
End Type
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As AnyAs Long

Public Function CopyContentDirectory(ByVal sDirSrc As String, ByVal sDirDest As String, Optional ByVal lHandle As Long = 0,  Optional ByVal bIncludeSubFolders As Boolean  = True, Optional ByVal bShowWindowsProgressBox As Boolean  = False, Optional ByVal bRenameIfExists As Boolean = False,  Optional ByVal bShowWindowsAskActionBox As Boolean  = True) As Boolean
'sDirSrc                    -> répertoire  source
'sDirDest                   ->  répertoire destination
'lHandle                    -> handle appelant (peut rester à  0)
'bIncludeSubFolders         -> copie  récursive, donc avec les sous-dossiers et leur contenu
'bShowWindowsProgressBox    -> affiche la progressbox  windows
'bRenameIfExists            -> pas  d'écrasement, renomme directement les nouveaux fichiers du  dossier
'bShowWindowsAskActionBox   -> boite de  dialogue "renommer écraser oui tous etc...". NB : si FALSE, il n'y a pas non  plus de ProgressBox
    On Error GoTo Err_Handler
    Dim tFOS As SHFILEOPSTRUCT
    
'   formate  les chemins
    If bIncludeSubFolders Then
        If RightB$(sDirSrc, 2) = "\" Then sDirSrc = LeftB$(sDirSrc, LenB(sDirSrc) - 2)
    Else
        If Not (RightB$(sDirSrc, 2) = "\"Then sDirSrc = sDirSrc & "\"
        sDirSrc = sDirSrc & "*.*"
    End If
    If Not (RightB$(sDirDest, 2) = "\"Then sDirDest = sDirDest & "\"
    
'    structure
    With tFOS
        .hWnd = lHandle
        .wFunc = FO_COPY
        .pFrom = sDirSrc & vbNullChar
        .pTo = sDirDest & vbNullChar
        .fFlags = CInt(SetFOSFlag(bIncludeSubFolders, bShowWindowsProgressBox,  bRenameIfExists, bShowWindowsAskActionBox, False, True))
        .fAborted = False
        .hNameMaps = 0&
        .sProgress = vbNullChar
    End With
'   API /  retour
    CopyContentDirectory = (SHFileOperation(tFOS) =  NOERROR)
    
Err_Handler:
'   en IDE on peut avoir un message "Mémoire insuffisante" en fin  d'action malgré la réussite
    If Err.Number = Then CopyContentDirectory =  True
End Function
Private Function SetFOSFlag(Optional ByVal bIncludeSubFolders As Boolean  = True, Optional ByVal bShowWindowsProgressBox As Boolean  = False, Optional ByVal bRenameIfExists As Boolean = False,  Optional ByVal bShowWindowsAskActionBox As Boolean  = False, Optional ByVal bAllowUndo As Boolean = False,  Optional ByVal bMulti  As Boolean = True) As  Long
    SetFOSFlag = FOF_WANTMAPPINGHANDLE Or  FOF_NOCONFIRMMKDIR
    If Not bIncludeSubFolders Then SetFOSFlag = SetFOSFlag  Or FOF_FILESONLY
    If Not bShowWindowsProgressBox Then SetFOSFlag = SetFOSFlag  Or FOF_SILENT
    If bRenameIfExists Then SetFOSFlag = SetFOSFlag Or FOF_RENAMEONCOLLISION
    If Not bShowWindowsAskActionBox Then SetFOSFlag = SetFOSFlag  Or FOF_NOCONFIRMATION
    If bAllowUndo Then SetFOSFlag = SetFOSFlag  Or FOF_ALLOWUNDO
    If bMulti Then SetFOSFlag = SetFOSFlag Or FOF_MULTIDESTFILES
End Function

Remarque :
bReussite = CopyContentDirectory("C:\test", "D:\test", lHandle:=0, bIncludeSubFolders:=True, bShowWindowsProgressBox:=True, bRenameIfExists:=False, bShowWindowsAskActionBox:=False)

Snippets en rapport avec : Fichier, Dossier, Copier, Sous-dossier



Codes sources en rapport avec : Fichier, Dossier, Copier, Sous-dossier

{Visual Basic, VB6, VB.NET, VB 2005} CRÉATION D'UN FICHIER AUTOEXTRACTIBLE
Cette source a pour but de montrer comment créer un fichier autoextractible contenant plusieurs fich...

{ColdFusion} COPIE DE FICHIERS (CUSTOM TAG)
ce custom tag vous permet de copier tous les fichiers d'un répertoire vers un autre. ...

{Visual Basic, VB6, VB.NET, VB 2005} GETNAMES : RÉCUPÈRE ET ÉCRIT TOUS LES NOMS DE FICHIERS D'UN DOSSIER
J'ai fait ce petit programme tout simple, qui aurait pu être créé par n'importe quel débutant, car j...

{PHP} LISTER LES DOSSIERS, SOUS-DOSSIERS ET NOMBRE DE FICHIERS
Une petite source sans prétention qui pourrait très bien figurer dans les snippets mais étant une pa...

{Visual Basic, VB6, VB.NET, VB 2005} SYNCHRONISE FICHIERS CLÉ AVEC LE PC
Voilà, comme je travaille sur une clé usb au boulot et sur mon pc chez moi je ne savais jamais les f...

{PHP} RENVOI UN DOSSIER DE NOM UNIQUE ET ALÉATOIRE
Petite fonction permettant de renvoyer un dossier disponible de nom aléatoire dans le chemin précisé...

{Visual Basic, VB6, VB.NET, VB 2005} DISTRIBUTION DE FICHIERS EN RESEAU
Utilitaire servant à distribuer des fichiers sur un réseau sans être obligé de configurer un deploie...

{Foxpro} RENOMMER LE PRÉFIXE DE TOUS LES FICHIERS D'UN DOSSIER
Vous disposez d'un dossier où les noms de plusieurs fichiers commencent par la même chaine. Vous vo...

{Visual Basic, VB6, VB.NET, VB 2005} EXPLORATEUR DE DOSSIER EN VB6
Ce code sert à naviguer dans les dossiers d'un disque en se servant d'un TreeView J'affiche les sou...

{Delphi} NOTIFICATION DES MODIFICATIONS DES FICHIERS D'UN DOSSIER
Ce code permet de tenir l'application au courant des modifications des fichiers dans un répertoire d...