Copie de dossiers et fichiers avec exclusions de certains types

pr0ph Messages postés 2 Date d'inscription samedi 26 janvier 2008 Statut Membre Dernière intervention 16 décembre 2010 - 16 déc. 2010 à 18:00
pr0ph Messages postés 2 Date d'inscription samedi 26 janvier 2008 Statut Membre Dernière intervention 16 décembre 2010 - 16 déc. 2010 à 21:23
Bonjour à tous !

Mon premier message ici, pour venir demander de l'aide, évidemment...

Je suis développeur tout à fait amateur et me débrouille pas trop mal dans les petits projets que je fais.
Mais je suis maintenant face à un mur, mes compétences actuelles ne me permettent pas de trouver la solution.

Je viens vous demander un coup de pouce pour m'aider à avancer !

En 2 mots, le projet est simple: c'est un programme automatisé qui fait un backup d'un poste utilisateur sur un serveur. En gros, il backup le desktop et le contenu de 'my documents' ainsi que quelques autres dossiers. Il est important pour moi qu'il prenne bien tous les fichiers, et dossiers, sous-dossiers et leur contenu.

J'utilise pour le moment la fonction "My.Computer.FileSystem.CopyDirectory" et mon programme est parfaitement fonctionnel de A à Z, il fait bien tout ce que je veux

Maintenant..voici ce que j'aimerais faire: exclure certains types de fichiers non professionnels et lourds: *.mp3, *.avi, *.divx, etc.

Je ne sais pour l'instant pas trop comment aborder le problème. Mon "intuition" me dit que malheureusement je vais devoir oublier la fonction CopyDirectory pourtant bien pratique vu qu'en une seule ligne je faisais exactement ce que je voulais, et à la place faire une itération parmi les fichiers, vérifier que chaque fichier ne contient pas les extensions que je ne désire pas, et ne faire la copie que si la condition est vérifiée..maintenant ce qui me fait peur, c'est de le faire pour chaque dossier et sous-dossier, la boucle me semble énorme et je ne suis pas sûr de savoir par quel bout je dois la prendre.

Est-ce que je me complique la vie, et y aurait-il une façon plus simple de procéder, ou est-ce que mon idée est la seule viable? Merci d'avance de me donner vos idées, suggestions ou critiques!

1 réponse

pr0ph Messages postés 2 Date d'inscription samedi 26 janvier 2008 Statut Membre Dernière intervention 16 décembre 2010
16 déc. 2010 à 21:23
Bon et bien je me suis retroussé les manches, et problème résolu :)

Pour ceux que ca intéresse, voici l'idée.
J'ai trouvé des infos super intéressantes sur DirectoryInfo et FileSystemInfo et j'ai créé une fonction les utilisant.

Un pseudo code très simplifié serait:

- Vérifier 1 par 1 les objets dans le dossier source
- Si le type d'objet est un fichier, vérifier qu'il fait partie des fichiers autorisés et si c'est le cas, le copier
- Si le type d'objet est un dossier, le créer
- On refait passer le dossier qu'on vient de créer dans la boucle de la Fonction

Ainsi, on a une fonction récursive qui copie tous les fichiers et sous dossiers de l'arborescence depuis la source fournie en argument, et compare les fichiers avec une autre fonction "CheckExt" booléenne qui va comparer l'extension du fichier en question avec une liste d'extensions bannies facile à mettre à jour.

Voici le code (désolé pour les commentaires en Anglais j'ai l'habitude de coder en Anglais..)

     Private Sub CopyDir(ByVal src As String, ByVal dest As String)

        Dim di As New DirectoryInfo(src)
        Dim fsi As FileSystemInfo
        Dim GetExt As IO.FileInfo
        Dim FileExt As String

        For Each fsi In di.GetFileSystemInfos() 'Get source content in a recursive loop, each object is analyzed
            Try
                Dim destName As String = Path.Combine(dest, fsi.Name) 'Determine the destination path/name
                If TypeOf fsi Is FileInfo Then 'Check if object is a file....
                    GetExt = My.Computer.FileSystem.GetFileInfo(fsi.FullName) 'Get the extension info
                    FileExt = GetExt.Extension 'Assign the extension to a String
                    If CheckExt(FileExt) = True Then 'Call CheckExt function to test if the extension is allowed
                        File.Copy(fsi.FullName, destName, True) 'It is allowed, we copy it
                    End If

                Else
                    Directory.CreateDirectory(destName) 'If it is not a file it is a directory, so we create it
                    CopyDir(fsi.FullName, destName) 'Do a function loop again for the folder we just created
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "File/folder copy loop problem!")
                Process.GetCurrentProcess.Kill()
            End Try
        Next

    End Sub
    Public Function CheckExt(ByVal TestExt As String) As Boolean 'Compares a file extension to a list to determine if it's allowed or not
        Dim AllowedExt As Boolean = True 'Initialise the AllowedExt variable, to true
        Try
            If TestExt.ToLower.Contains(".avi") Then 'Start checking the forbidden extensions. .ToLower because Contains() is case sensitive!
                AllowedExt = False 'Then turn the variable to False
            End If
            If TestExt.ToLower.Contains(".divx") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".jpeg") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".jpg") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mp3") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mpeg") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mpg") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".bmp") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".gif") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".wav") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".wmv") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".wma") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".ogg") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mp4") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".m4p") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mp1") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mp2") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".png") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mov") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".m4v") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".m4a") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".tif") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".tiff") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".aac") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".aiff") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".aif") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".aifc") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".3gp") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".asf") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".m1v") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".m2v") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mkv") Then
                AllowedExt = False
            End If
            If TestExt.ToLower.Contains(".mpe") Then
                AllowedExt = False
            End If
            Return AllowedExt 'Function returns True if no test was failed, otherwise False.
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "File extension comparison problem!")
            Process.GetCurrentProcess.Kill()
        End Try
        
    End Function
0
Rejoignez-nous