Procédure pas à pas : manipulation de fichiers et de répertoires en Visual Basic

Cette procédure pas à pas présente les notions de base d’E/S de fichier dans Visual Basic. Elle décrit comment créer une petite application qui répertorie et examine des fichiers texte dans un répertoire. Pour chaque fichier texte sélectionné, l’application fournit des attributs de fichier et la première ligne de contenu. Elle comprend une option pour écrire des informations dans un fichier journal.

Cette procédure pas à pas utilise des membres de My.Computer.FileSystem Object, qui sont disponibles dans Visual Basic. Consultez la rubrique FileSystem (éventuellement en anglais) pour plus d'informations. À la fin de la procédure pas à pas, un exemple équivalent est fourni, qui utilise des classes de l’espace de noms System.IO.

Notes

Il est possible que pour certains des éléments de l'interface utilisateur de Visual Studio, votre ordinateur affiche des noms ou des emplacements différents de ceux indiqués dans les instructions suivantes. L'édition de Visual Studio dont vous disposez et les paramètres que vous utilisez déterminent ces éléments. Pour plus d’informations, consultez Personnalisation de l’IDE.

Pour créer le projet

  1. Dans le menu Fichier, cliquez sur Nouveau projet.

    La boîte de dialogue Nouveau projet apparaît.

  2. Dans le volet Modèles installés, développez Visual Basic, puis cliquez sur Windows. Dans le volet Modèles du milieu, cliquez sur Application Windows Forms.

  3. Dans la zone Nom, tapez FileExplorer pour définir le nom de projet, puis cliquez sur OK.

    Visual Studio ajoute le projet à l’Explorateur de solutions et le concepteur Windows Forms s’ouvre.

  4. Ajoutez au formulaire les contrôles répertoriés dans le tableau ci-après et définissez les valeurs de propriété correspondantes.

    Control Propriété Valeur
    ListBox Nom filesListBox
    Button Nom

    Texte
    browseButton

    Parcourir
    Button Nom

    Texte
    examineButton

    Examiner
    CheckBox Nom

    Texte
    saveCheckBox

    Enregistrer les résultats
    FolderBrowserDialog Nom FolderBrowserDialog1

Pour sélectionner un dossier et répertorier les fichiers dans un dossier

  1. Créez un gestionnaire d’événements Click pour browseButton en double-cliquant sur le contrôle sur le formulaire. L'éditeur de code s'ouvre.

  2. Ajoutez le code ci-après au gestionnaire d'événements Click.

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    

    L’appel de FolderBrowserDialog1.ShowDialog ouvre la boîte de dialogue Rechercher un dossier. Une fois que l’utilisateur a cliqué sur OK, la propriété SelectedPath est envoyée en tant qu’argument à la méthode ListFiles, qui est ajoutée à l’étape suivante.

  3. Ajoutez la méthode ListFiles suivante.

    Private Sub ListFiles(ByVal folderPath As String)
        filesListBox.Items.Clear()
    
        Dim fileNames = My.Computer.FileSystem.GetFiles(
            folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
    
        For Each fileName As String In fileNames
            filesListBox.Items.Add(fileName)
        Next
    End Sub
    

    Ce code efface d’abord le contrôle ListBox.

    La méthode GetFiles récupère ensuite une collection de chaînes, une pour chaque fichier dans le répertoire. La méthode GetFiles accepte un argument de modèle de recherche pour récupérer les fichiers qui correspondent à un modèle particulier. Dans cet exemple, seuls les fichiers ayant l’extension .txt sont retournés.

    Les chaînes qui sont retournées par la méthode GetFiles sont ensuite ajoutées à ListBox.

  4. Exécutez l’application. Cliquez sur le bouton Parcourir . Dans la boîte de dialogue Rechercher un dossier, accédez à un dossier qui contient des fichiers .txt, puis sélectionnez le dossier et cliquez sur OK.

    ListBox contient une liste des fichiers.txt du dossier sélectionné.

  5. Arrêtez l’exécution de l’application.

Pour obtenir les attributs d’un fichier et le contenu d’un fichier texte

  1. Créez un gestionnaire d’événements Click pour examineButton en double-cliquant sur le contrôle sur le formulaire.

  2. Ajoutez le code ci-après au gestionnaire d'événements Click.

    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If
    
    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString
    
    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If
    
    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)
    
    ' Show the file information.
    MessageBox.Show(fileInfoText)
    

    Le code vérifie qu’un élément est sélectionné dans le contrôle ListBox. Il obtient ensuite l’entrée du chemin du fichier à partir de ListBox. La méthode FileExists est utilisée pour vérifier si le fichier existe toujours.

    Le chemin du fichier est envoyé en tant qu’argument à la méthode GetTextForOutput, qui est ajoutée à l’étape suivante. Cette méthode retourne une chaîne qui contient des informations sur le fichier. Les informations sur le fichier s’affichent dans un élément MessageBox.

  3. Ajoutez la méthode GetTextForOutput suivante.

    Private Function GetTextForOutput(ByVal filePath As String) As String
        ' Verify that the file exists.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            Throw New Exception("File Not Found: " & filePath)
        End If
    
        ' Create a new StringBuilder, which is used
        ' to efficiently build strings.
        Dim sb As New System.Text.StringBuilder()
    
        ' Obtain file information.
        Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
    
        ' Add file attributes.
        sb.Append("File: " & thisFile.FullName)
        sb.Append(vbCrLf)
        sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
        sb.Append(vbCrLf)
        sb.Append("Size: " & thisFile.Length.ToString & " bytes")
        sb.Append(vbCrLf)
    
        ' Open the text file.
        Dim sr As System.IO.StreamReader =
            My.Computer.FileSystem.OpenTextFileReader(filePath)
    
        ' Add the first line from the file.
        If sr.Peek() >= 0 Then
            sb.Append("First Line: " & sr.ReadLine())
        End If
        sr.Close()
    
        Return sb.ToString
    End Function
    

    Le code utilise la méthode GetFileInfo pour obtenir des paramètres de fichier. Les paramètres de fichier sont ajoutés à un StringBuilder.

    La méthode OpenTextFileReader lit le contenu du fichier dans un StreamReader. La première ligne du contenu est obtenue à partir du StreamReader et est ajoutée au StringBuilder.

  4. Exécutez l’application. Cliquez sur Parcourir et recherchez un dossier qui contient des fichiers .txt. Cliquez sur OK.

    Sélectionnez un fichier dans le contrôle ListBox, puis cliquez sur Examiner. MessageBox affiche les informations sur le fichier.

  5. Arrêtez l’exécution de l’application.

Pour ajouter une entrée de journal

  1. Ajoutez le code suivant à la fin du gestionnaire d’événements examineButton_Click.

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
    
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf
    
        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
    

    Le code définit le chemin du fichier journal de sorte que ce dernier soit placé dans le même répertoire que celui du fichier sélectionné. Le texte de l’entrée de journal prend comme valeur la date et l’heure actuelles, suivies des informations sur le fichier.

    La méthode WriteAllText, avec l’argument append défini sur True, est utilisée pour créer l’entrée de journal.

  2. Exécutez l’application. Accédez à un fichier texte, sélectionnez-le dans le contrôle ListBox, cochez la case Enregistrer les résultats, puis cliquez sur Examiner. Vérifiez que l’entrée de journal est écrite dans le fichier log.txt.

  3. Arrêtez l’exécution de l’application.

Pour utiliser le répertoire actif

  1. Créez un gestionnaire d’événements pour Form1_Load en double-cliquant sur le formulaire.

  2. Ajoutez le code suivant au gestionnaire d’événements.

    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
    

    Ce code définit le répertoire actif comme le répertoire par défaut de l’Explorateur de dossiers.

  3. Exécutez l’application. Quand vous cliquez pour la première fois sur Parcourir, la boîte de dialogue Rechercher un dossier affiche le répertoire actif.

  4. Arrêtez l’exécution de l’application.

Pour activer des contrôles de manière sélective

  1. Ajoutez la méthode SetEnabled suivante.

    Private Sub SetEnabled()
        Dim anySelected As Boolean =
            (filesListBox.SelectedItem IsNot Nothing)
    
        examineButton.Enabled = anySelected
        saveCheckBox.Enabled = anySelected
    End Sub
    

    La méthode SetEnabled active ou désactive les contrôles, selon qu’un élément est sélectionné ou non dans le contrôle ListBox.

  2. Créez un gestionnaire d’événements SelectedIndexChanged pour filesListBox en double-cliquant sur le contrôle ListBox sur le formulaire.

  3. Ajoutez un appel à SetEnabled dans le nouveau gestionnaire d’événements filesListBox_SelectedIndexChanged.

  4. Ajoutez un appel à SetEnabled à la fin du gestionnaire d’événements browseButton_Click.

  5. Ajoutez un appel à SetEnabled à la fin du gestionnaire d’événements Form1_Load.

  6. Exécutez l’application. La case Enregistrer les résultats et le bouton Examiner sont désactivés si aucun élément n’est sélectionné dans le contrôle ListBox.

Exemple complet de l’utilisation de My.Computer.FileSystem

L’exemple complet se trouve ci-dessous.


' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    SetEnabled()
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames = My.Computer.FileSystem.GetFiles(
        folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        My.Computer.FileSystem.OpenTextFileReader(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

Exemple complet de l’utilisation de System.IO

L’exemple équivalent suivant utilise des classes de l’espace de noms System.IO au lieu d’utiliser des objets My.Computer.FileSystem.


' This example uses classes from the System.IO namespace.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath =
        System.IO.Directory.GetCurrentDirectory()

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
        SetEnabled()
    End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames As String() =
        System.IO.Directory.GetFiles(folderPath,
            "*.txt", System.IO.SearchOption.TopDirectoryOnly)

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If System.IO.File.Exists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String =
            System.IO.Path.GetDirectoryName(filePath)
        Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

        ' Append text to the log file.
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        System.IO.File.AppendAllText(logFilePath, logText)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If System.IO.File.Exists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As New System.IO.FileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        System.IO.File.OpenText(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

Voir aussi