Postupy: Čtení z textových souborů s oddělovači v jazyce Visual Basic

Objekt TextFieldParser poskytuje způsob, jak snadno a efektivně analyzovat strukturované textové soubory, jako jsou protokoly. Vlastnost TextFieldType definuje, zda se jedná o soubor s oddělovači nebo soubor s poli s pevnou šířkou textu.

Analýza textového souboru s oddělovači

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

    Using MyReader As New Microsoft.VisualBasic.
                          FileIO.TextFieldParser(
                            "C:\TestFolder\test.txt")
    
  2. TextField Definujte typ a oddělovač. Následující kód definuje TextFieldType vlastnost jako Delimited a oddělovač jako ",".

    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
  3. Projděte pole v souboru. Pokud jsou některé řádky poškozené, nahlaste chybu a pokračujte v analýze. Následující kód prochází souborem a zobrazuje jednotlivá pole a hlásí všechna pole, která jsou nesprávně naformátovaná.

    
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.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.txt.

Using MyReader As New Microsoft.VisualBasic.
                      FileIO.TextFieldParser(
                        "C:\TestFolder\test.txt")
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.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é