Comment : lire des fichiers texte avec plusieurs formats dans Visual Basic
Mise à jour : novembre 2007
L'objet TextFieldParser permet d'analyser facilement et efficacement les fichiers texte structurés, tels que les journaux. Vous pouvez traiter un fichier à plusieurs formats à l'aide de la méthode PeekChars pour déterminer le format de chaque ligne à mesure que vous analysez le fichier.
Pour analyser un fichier texte avec plusieurs formats
Définissez le format attendu et le format utilisé lorsqu'une erreur est signalée.
Dim StdFormat As Integer()= {5,10,11,-1} Dim ErrorFormat As Integer() = {5,5,-1}
Créez un objet TextFieldParser en définissant la largeur et le format.
Using MyReader As New _ Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth
Parcourez les lignes en testant le format avant la lecture.
Dim CurrentRow As String() While Not MyReader.EndOfData Try Dim RowType As String = MyReader.PeekChars(3) If String.Compare(RowType, "Err") = 0 Then ' If this line describes an error, the format of ' the row will be different. MyReader.SetFieldWidths(ErrorFormat) CurrentRow = MyReader.ReadFields MyReader.SetFieldWidths(StdFormat) Else 'Otherwise parse the fields normally CurrentRow = MyReader.ReadFields For Each newString As String In CurrentRow My.Computer.FileSystem.WriteAllText _ ("newFile.txt", newString, True) Next End If
Écrivez les erreurs dans la console.
Catch ex As _ Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & " is invalid.") End Try End While End Using
Exemple
Cet exemple lit le fichier testfile.txt.
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = MyReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(ErrorFormat)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Programmation fiable
Les conditions ci-dessous peuvent générer une exception :
Une ligne ne peut pas être analysée avec le format spécifié (MalformedLineException). Le message d'exception spécifie la ligne qui provoque l'exception, tandis que la propriété TextFieldParser.ErrorLine est assignée au texte contenu dans la ligne.
Le fichier spécifié n'existe pas (FileNotFoundException).
Une situation de niveau de confiance partiel dans laquelle l'utilisateur n'a pas les autorisations suffisantes pour accéder au fichier. (SecurityException).
Le chemin d'accès est trop long (PathTooLongException
L'utilisateur n'a pas les autorisations suffisantes pour accéder au fichier (UnauthorizedAccessException).
Voir aussi
Tâches
Comment : lire des fichiers texte délimités par des virgules dans Visual Basic
Comment : lire des fichiers texte de largeur fixe dans Visual Basic
Concepts
Analyse des fichiers texte avec l'objet TextFieldParser
Référence
TextFieldParser.PeekChars, méthode
My.Computer.FileSystem.WriteAllText, méthode