Share via


Cómo: Leer archivos de texto con varios formatos en Visual Basic

Actualización: noviembre 2007

El objeto TextFieldParser proporciona una manera de analizar con facilidad y eficiencia archivos de texto estructurados, como por ejemplo los registros. Puede procesar un archivo con varios formatos utilizando el método PeekChars para determinar el formato de cada línea a medida que se va analizando el archivo.

Para analizar un archivo de texto con varios formatos

  1. Defina el formato esperado y el formato utilizado cuando se cree un informe un error.

    Dim StdFormat As Integer()= {5,10,11,-1}
    Dim ErrorFormat As Integer() = {5,5,-1}
    
  2. Cree un nuevo objeto TextFieldParser, definiendo su ancho y su formato.

    Using MyReader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    
  3. Recorra en iteración las filas, probando el formato antes de leerlas.

    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. Escriba los errores en la consola.

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

Ejemplo

Este ejemplo lee del archivo 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

Programación eficaz

Las condiciones siguientes pueden producir una excepción:

Vea también

Tareas

Cómo: Leer archivos de texto delimitado por comas en Visual Basic

Cómo: Leer archivos de texto de ancho fijo en Visual Basic

Conceptos

Analizar archivos de texto con el objeto TextFieldParser

Referencia

TextFieldParser (Objeto)

TextFieldParser.PeekChars (Método)

MalformedLineException

My.Computer.FileSystem.WriteAllText (Método)

TextFieldParser.EndOfData (Propiedad)

TextFieldParser.TextFieldType (Propiedad)