Condividi tramite


Procedura: leggere file di testo con più formati in Visual Basic

Aggiornamento: novembre 2007

L'oggetto TextFieldParser consente di analizzare in modo facile ed efficace i file di testo strutturati, ad esempio i log. È possibile elaborare un file con più formati utilizzando il metodo PeekChars per determinare il formato di ciascuna riga mentre si analizza il file.

Per analizzare un file di testo con più formati

  1. Definire il formato previsto e il formato utilizzato quando viene restituito un errore.

    Dim StdFormat As Integer()= {5,10,11,-1}
    Dim ErrorFormat As Integer() = {5,5,-1}
    
  2. Creare un nuovo oggetto TextFieldParser, definendone l'ampiezza e il formato.

    Using MyReader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    
  3. Far scorrere le righe, verificando il formato prima di eseguire la lettura.

    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. Scrivere gli errori nella console.

          Catch ex As _
          Microsoft.VisualBasic.FileIO.MalformedLineException
             MsgBox("Line " & ex.Message & " is invalid.")
          End Try
       End While
    End Using
    

Esempio

Nell'esempio riportato di seguito la lettura viene eseguita dal file 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

Programmazione efficiente

Le seguenti condizioni possono generare un'eccezione:

Vedere anche

Attività

Procedura: leggere file di testo delimitati da virgola in Visual Basic

Procedura: leggere file di testo a larghezza fissa in Visual Basic

Concetti

Analisi dei file di testo con l'oggetto TextFieldParser

Riferimenti

Oggetto TextFieldParser

Metodo TextFieldParser.PeekChars

MalformedLineException

Metodo My.Computer.FileSystem.WriteAllText

Proprietà TextFieldParser.EndOfData

Proprietà TextFieldParser.TextFieldType