Postupy: Čtení z textových souborů s pevnou šířkou v jazyce Visual Basic

Objekt TextFieldParser poskytuje způsob, jak snadno a efektivně analyzovat strukturované textové soubory, jako jsou protokoly.

Vlastnost TextFieldType definuje, zda parsovaný soubor je soubor s oddělovači nebo soubor, který má pole s pevnou šířkou textu. V textovém souboru s pevnou šířkou může mít pole na konci proměnnou šířku. Chcete-li určit, že pole na konci má proměnnou šířku, definujte ji tak, aby měla šířku menší nebo rovno nule.

Analýza textového souboru s pevnou šířkou

  1. Vytvořte novou TextFieldParser. Následující kód vytvoří pojmenovaný TextFieldParserReader a otevře soubor test.log.

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldType Definujte vlastnost jako FixedWidth, definující šířku a formát. Následující kód definuje sloupce textu; První je široký 5 znaků, druhý 10, třetí 11 a čtvrtý je proměnlivá šířka.

    Reader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. Projděte pole v souboru. Pokud jsou nějaké řádky poškozené, nahlaste chybu a pokračujte v analýze.

    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    
  4. Zavřete While a Using bloky s End While a End Using.

        End While
    End Using
    

Příklad

Tento příklad čte ze souboru test.log.

Using Reader As New Microsoft.VisualBasic.FileIO.
   TextFieldParser("C:\TestFolder\test.log")

    Reader.TextFieldType =
       Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
End Using

Robustní programování

Následující podmínky mohou způsobit výjimku:

Viz také