Como: Ler From Texto Files with Multiple formatos no Visual Basic

O objeto TextFieldParser fornece uma maneira para facilmente e com eficiência analisar arquivos texto estruturados, como logs.Você pode processar um arquivo com vários formatos usando o método PeekChars para determinar o formato de cada linha conforme você analisa através do arquivo.

Para analisar um arquivo de texto com vários formatos

  1. Defina o formato esperado e o formato usado quando um erro é relatado.

    Dim StdFormat As Integer()= {5,10,11,-1}
    Dim ErrorFormat As Integer() = {5,5,-1}
    
  2. Crie um novo objeto TextFieldParser, definindo a largura e o formato.

    Using MyReader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    
  3. Percorra as linhas, testando seus formatos antes da leitura.

    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. Grave erros no console.

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

Exemplo

Este exemplo lê a partir do arquivo 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

Programação robusta

As seguintes condições podem causar uma exceção:

Consulte também

Tarefas

Como: Leitura de arquivos de texto delimitado por vírgula no Visual Basic

Como: Leitura de arquivos de texto de largura fixa no Visual Basic

Conceitos

Analisar Arquivos de Texto com o Objeto TextFieldParser

Referência

TextFieldParser Objeto

Método TextFieldParser.PeekChars.

MalformedLineException

My.Computador.FileSystem.WriteAllText método

Propriedade TextFieldParser.EndOfData

Propriedade TextFieldParser.TextFieldType