Cómo: Leer archivos de texto con varios formatos en Visual Basic
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
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.
Defina el formato esperado y el formato utilizado cuando se cree un informe un error. La última entrada en cada matriz es -1, por consiguiente se supone 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}
Cree un nuevo objeto TextFieldParser, definiendo su ancho y su formato.
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth MyReader.FieldWidths = stdFormat
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()
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 eficaz
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 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 es demasiado larga (PathTooLongException).
El usuario no tiene permisos suficientes para el acceso al archivo (UnauthorizedAccessException).
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
Referencia
Conceptos
Analizar archivos de texto con el objeto TextFieldParser (Visual Basic)