Compartir a través de


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

El TextFieldParser objeto proporciona una manera de analizar archivos de texto estructurados de forma fácil y eficaz, como registros. Puede procesar un archivo con varios formatos mediante el PeekChars método para determinar el formato de cada línea a medida que analiza el archivo.

Para analizar un archivo de texto con varios formatos

  1. Agregue un archivo de texto denominado testfile.txt al proyecto. Agregue el siguiente contenido al archivo de texto:

    Err  1001 Cannot access resource.
    Err  2014 Resource not found.
    Acc  10/03/2009User1      Administrator.
    Err  0323 Warning: Invalid access attempt.
    Acc  10/03/2009User2      Standard user.
    Acc  10/04/2009User2      Standard user.
    
  2. Defina el formato esperado y el formato usado cuando se notifique un error. La última entrada de cada matriz es -1, por lo que se supone que el último campo es de ancho variable. Esto ocurre cuando la última entrada de la matriz es menor o igual que 0.

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. Cree un nuevo TextFieldParser objeto y defina el ancho y el formato.

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. Recorra las filas y pruebe el formato antes de leerlo.

    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = 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)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
    
  5. 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

A continuación se muestra un ejemplo completo que lee del archivo testfile.txt:

Dim stdFormat As Integer() = {5, 10, 11, -1}
Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = stdFormat
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = 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)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
        Catch ex As FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
    End While
End Using
Console.ReadLine()

Programación sólida

Las condiciones siguientes pueden provocar una excepción:

  • No se puede analizar una fila con el formato especificado (MalformedLineException). El mensaje de excepción especifica la línea que provoca la excepción, mientras que la ErrorLine propiedad se asigna al texto contenido en la línea.
  • El archivo especificado no existe (FileNotFoundException).
  • Situación de confianza parcial en la que el usuario no tiene permisos suficientes para acceder al archivo. (SecurityException).
  • La ruta de acceso del archivo es demasiado larga (PathTooLongException).
  • El usuario no tiene permisos suficientes para acceder al archivo (UnauthorizedAccessException).

Consulte también