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

  1. 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}
    
  2. 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
    
  3. 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
    
  4. É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 :

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, objet

TextFieldParser.PeekChars, méthode

MalformedLineException

My.Computer.FileSystem.WriteAllText, méthode

TextFieldParser.EndOfData, propriété

TextFieldParser.TextFieldType, propriété