Partilhar via


Como: ler a partir de arquivos de texto delimitados por vírgulas no Visual Basic

O TextFieldParser objeto fornece uma maneira fácil e eficiente de analisar arquivos de texto estruturados, como logs. A TextFieldType propriedade define se é um arquivo delimitado ou com campos de texto de largura fixa.

Para analisar um arquivo de texto delimitado por vírgulas

  1. Crie um novo TextFieldParserarquivo . O código a seguir cria o TextFieldParser nome MyReader e abre o arquivo test.txt.

    Using MyReader As New Microsoft.VisualBasic.
                          FileIO.TextFieldParser(
                            "C:\TestFolder\test.txt")
    
  2. Defina o tipo e o TextField delimitador. O código a seguir define a TextFieldType propriedade como Delimited e o delimitador como ",".

    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
  3. Percorra os campos no arquivo. Se alguma linha estiver corrompida, reporte um erro e continue analisando. O código a seguir percorre o arquivo, exibindo cada campo por sua vez e relatando quaisquer campos formatados incorretamente.

    
    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. Feche os While blocos e Using com End While e End Using.

        End While
    End Using
    

Exemplo

Este exemplo lê o arquivo 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

Programação robusta

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

Consulte também