Guide pratique pour lire des fichiers texte ayant plusieurs formats en Visual Basic

L’objet TextFieldParser permet d’analyser facilement et efficacement les fichiers texte structurés, tels que les journaux. Vous pouvez traiter un fichier contenant plusieurs formats en utilisant 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

  1. Ajoutez un fichier texte nommé testfile.txt à votre projet. Ajoutez le contenu suivant au fichier texte :

    Err  1001 Cannot access resource.
    Err  2014 Resource not found.
    Acc  10/03/2009User1      Administrator.
    Err  0323 Warning: Invalid access attempt.
    Acc  10/03/2009User2      Standard user.
    Acc  10/04/2009User2      Standard user.
    
  2. Définissez le format attendu et le format utilisé quand une erreur est signalée. La dernière entrée dans chaque tableau étant -1, le dernier champ est supposé avoir une largeur variable. Cela se produit quand la dernière entrée du tableau est inférieure ou égale à 0.

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. Créez un nouvel objet TextFieldParser en définissant la largeur et le format.

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. Parcourez les lignes en boucle, en testant le format avant la lecture.

    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = 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)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
    
  5. É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

Voici l’exemple complet qui permet de lire le fichier testfile.txt :

Dim stdFormat As Integer() = {5, 10, 11, -1}
Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = stdFormat
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = 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)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
        Catch ex As FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
    End While
End Using
Console.ReadLine()

Programmation fiable

Les conditions ci-dessous peuvent générer une exception.

  • Une ligne ne peut pas être analysée à l’aide du format spécifié (MalformedLineException). Le message d’exception spécifie la ligne qui provoque l’exception, tandis que la propriété ErrorLine est assignée au texte contenu dans la ligne.
  • Le fichier spécifié n’existe pas (FileNotFoundException).
  • Situation de confiance partielle dans laquelle l’utilisateur ne dispose pas des autorisations suffisantes pour accéder au fichier (SecurityException).
  • Le chemin est trop long (PathTooLongException).
  • L’utilisateur ne dispose pas des autorisations suffisantes pour accéder au fichier (UnauthorizedAccessException).

Voir aussi