Procedimiento de lectura de archivos de texto con varios formatos en Visual Basic

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

Para analizar un archivo de texto con varios formatos

  1. Agregue un archivo de texto denominado testfile.txt al proyecto. Agregue el contenido siguiente 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 cree un informe un error. La última entrada en cada matriz es -1, por consiguiente se presupone que el último campo es de ancho variable. Esto se produce cuando la última entrada en 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 objeto TextFieldParser que defina el ancho y el formato.

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. Recorra en iteración las filas, probando el formato antes de leerlas.

    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 proporciona el 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 utilizando el formato especificado (MalformedLineException). El mensaje de excepción especifica la línea que produce la excepción y la propiedad ErrorLine se asigna al texto contenido en la línea.
  • El archivo especificado no existe (FileNotFoundException).
  • Una situación de confianza parcial en la que el usuario no tiene los permisos necesarios para tener acceso al archivo. (SecurityException).
  • La ruta de acceso del archivo es demasiado larga (PathTooLongException).
  • El usuario no tiene permisos suficientes para acceder al archivo (UnauthorizedAccessException).

Vea también