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 relatives aux 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. Il existe une option pour écrire les informations dans un fichier journal.

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

Notes

Il est possible que votre ordinateur affiche des noms ou des emplacements différents pour certains des éléments d'interface utilisateur de Visual Studio 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 Paramètres Visual Studio.

Pour créer le projet

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

    La boîte de dialogue Nouveau projet s'affiche.

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

  3. Dans la zone Nom, tapez FileExplorer pour définir le nom du 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 suivant et définissez les valeurs de propriété correspondantes.

    Contrôle

    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 de type Click pour browseButton en double-cliquant sur le contrôle situé sur le formulaire. L'éditeur de code s'ouvre.

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

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

    L'appel FolderBrowserDialog1.ShowDialog ouvre la boîte de dialogue Rechercher un dossier. Lorsque l'utilisateur clique sur OK, la propriété SelectedPath est envoyée comme un argument à la méthode ListFiles, qui est ajoutée dans 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 ListBox.

    La méthode GetFiles extrait 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 extraire les fichiers qui correspondent à un modèle particulier. Dans cet exemple, seuls les fichiers avec l'extension .txt sont retournés.

    Les chaînes retournées par la méthode GetFiles sont ensuite ajoutées au 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 ce dossier et cliquez sur OK.

    Le ListBox contient la liste des fichiers .txt dans le 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 de type Click pour examineButton en double-cliquant sur le contrôle situé sur le formulaire.

  2. Ajoutez le code suivant 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 ListBox. Il obtient alors l'entrée de chemin d'accès de fichier du ListBox. La méthode FileExists est utilisée pour vérifier si le fichier existe encore.

    Le chemin d'accès du fichier est envoyé comme un argument à la méthode GetTextForOutput, qui est ajoutée dans l'étape suivante. Cette méthode retourne une chaîne qui contient les informations sur le fichier. Les informations sur le fichier s'affichent dans un 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 les paramètres du fichier. Ces paramètres 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 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 ListBox, puis cliquez sur Examiner. Un MessageBox affiche les informations sur le fichier.

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

Pour ajouter une entrée du 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 d'accès 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 ayant comme valeur 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 ListBox, activez la case à cocher 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 la recherche des dossiers.

  3. Exécutez l'application. Lorsque 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 ListBox.

  2. Créez un gestionnaire d'événements de type SelectedIndexChanged pour filesListBox en double-cliquant sur le contrôle ListBox situé 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 à cocher Enregistrer les résultats et le bouton Examiner sont désactivés si aucun élément n'est sélectionné dans 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

Tâches

Procédure pas à pas : manipulation de fichiers à l'aide de méthodes du .NET Framework (Visual Basic)

Référence

System.IO

FileSystem

CurrentDirectory

Historique des modifications

Date

Historique

Motif

Décembre 2010

Révision des exemples et de la procédure pas à pas.

amélioration

Août 2010

Mise à jour et correction de l'exemple de code.

Commentaires client.