Notes
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Cette procédure pas à pas fournit une introduction aux principes fondamentaux des E/S de fichier en Visual Basic. Il décrit comment créer une petite application qui répertorie et examine les 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 permettant d’é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. Pour plus d’informations, consultez FileSystem. À la fin de la procédure pas à pas, un exemple équivalent est fourni, qui utilise des classes de l’espace de noms System.IO.
Remarque
Votre ordinateur peut afficher différents noms ou emplacements pour certains des éléments de l’interface utilisateur Visual Studio dans les instructions suivantes. L’édition Visual Studio que vous avez et les paramètres que vous utilisez déterminent ces éléments. Pour plus d’informations, consultez Personnaliser l’IDE.
Pour créer le projet
Dans le menu Fichier, cliquez sur Nouveau projet.
La boîte de dialogue Nouveau projet apparaît.
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.
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.
Ajoutez les contrôles du tableau suivant au formulaire et définissez les valeurs correspondantes pour leurs propriétés.
Contrôle Propriété Valeur Zone de liste Nom filesListBox
bouton Nom
TextebrowseButton
Parcourirbouton Nom
TexteexamineButton
Examinercase à cocher Nom
TextesaveCheckBox
Enregistrer les résultatsFolderBrowserDialog Nom FolderBrowserDialog1
Pour sélectionner un dossier et répertorier des fichiers dans un dossier
Créez un gestionnaire d'événements
Click
pourbrowseButton
en double-cliquant sur le contrôle du formulaire. L’Éditeur de code s’ouvre.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 de
FolderBrowserDialog1.ShowDialog
ouvre la boîte de dialogue Rechercher un dossier. Une fois que l’utilisateur clique sur OK, la SelectedPath propriété est envoyée en tant qu’argument à laListFiles
méthode, qui est ajoutée à l’étape suivante.Ajoutez la méthode suivante
ListFiles
.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 listBox.
La GetFiles méthode récupère ensuite une collection de chaînes, une pour chaque fichier du répertoire. La
GetFiles
méthode accepte un argument de modèle de recherche pour récupérer des fichiers qui correspondent à un modèle particulier. Dans cet exemple, seuls les fichiers qui ont l’extension .txt sont retournés.Les chaînes retournées par la
GetFiles
méthode sont ensuite ajoutées à ListBox.Exécutez l’application. Cliquez sur le bouton Parcourir. Dans la boîte de dialogue Rechercher un dossier, accédez à un dossier contenant .txt fichiers, puis sélectionnez le dossier, puis cliquez sur OK.
Le
ListBox
contient une liste de fichiers .txt dans le dossier sélectionné.Arrêtez l’exécution de l’application.
Pour obtenir des attributs d’un fichier et du contenu à partir d’un fichier texte
Créez un gestionnaire d'événements
Click
pourexamineButton
en double-cliquant sur le contrôle du formulaire.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 ensuite le chemin d'accès du fichier à partir duListBox
. La FileExists méthode est utilisée pour vérifier si le fichier existe toujours.Le chemin d’accès au fichier est envoyé en tant qu’argument à la
GetTextForOutput
méthode, qui est ajouté à l’étape suivante. Cette méthode retourne une chaîne qui contient des informations de fichier. Les informations de fichier s’affichent dans un MessageBox.Ajoutez la méthode suivante
GetTextForOutput
.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 GetFileInfo méthode pour obtenir des paramètres de fichier. Les paramètres de fichier sont ajoutés à un StringBuilder.
La OpenTextFileReader méthode lit le contenu du fichier dans un StreamReader. La première ligne du contenu est obtenue à partir du
StreamReader
et est ajoutée auStringBuilder
.Exécutez l’application. Cliquez sur Parcourir, puis accédez à un dossier contenant des fichiers .txt. Cliquez sur OK.
Sélectionnez un fichier dans le
ListBox
fichier, puis cliquez sur Examiner. AMessageBox
affiche les informations de fichier.Arrêtez l’exécution de l’application.
Pour ajouter une entrée de journal
Ajoutez le code suivant à la fin du
examineButton_Click
gestionnaire d’événements.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 pour placer le fichier journal dans le même répertoire que celui du fichier sélectionné. Le texte de l’entrée de journal est établi à la date et l’heure actuelles, suivies par les informations du fichier.
La méthode WriteAllText, avec l’argument
append
défini surTrue
, est utilisée pour créer une entrée dans le journal.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 fichierlog.txt
.Arrêtez l’exécution de l’application.
Pour utiliser le répertoire actuel
Créez un gestionnaire d'événements pour
Form1_Load
en double-cliquant sur le formulaire.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 par défaut du navigateur de dossiers sur le répertoire actif.
Exécutez l’application. Lorsque vous cliquez sur Parcourir la première fois, la boîte de dialogue Parcourir le dossier s’ouvre sur le répertoire actif.
Arrêtez l’exécution de l’application.
Pour activer de manière sélective les contrôles
Ajoutez la méthode suivante
SetEnabled
.Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub
La
SetEnabled
méthode active ou désactive les contrôles selon qu’un élément est sélectionné dans leListBox
.Créez un gestionnaire d'événements
SelectedIndexChanged
pourfilesListBox
en double-cliquant sur le contrôleListBox
dans le formulaire.Ajoutez un appel à
SetEnabled
dans le nouveau gestionnaire d’événementsfilesListBox_SelectedIndexChanged
.Ajoutez un appel à
SetEnabled
à la fin du gestionnaire d'événementsbrowseButton_Click
.Ajoutez un appel à
SetEnabled
à la fin du gestionnaire d'événementsForm1_Load
.Exécutez l’application. La case à cocher Enregistrer les résultats et le bouton Examiner sont désactivés si un élément n’est pas sélectionné dans le
ListBox
.
Exemple complet utilisant My.Computer.FileSystem
Voici l’exemple complet.
' 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 utilisant System.IO
L’exemple équivalent suivant utilise des classes du namespace 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