Condividi tramite


Procedura: Leggere da file di testo con più formati in Visual Basic

L'oggetto TextFieldParser consente di analizzare in modo semplice ed efficiente i file di testo strutturati, ad esempio i log. È possibile elaborare un file con più formati usando il PeekChars metodo per determinare il formato di ogni riga durante l'analisi del file.

Per analizzare un file di testo con più formati

  1. Aggiungere un file di testo denominato testfile.txt al progetto. Aggiungere il contenuto seguente al file di testo:

    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. Definire il formato previsto e il formato utilizzato quando viene segnalato un errore. L'ultima voce in ogni matrice è -1, pertanto si presuppone che l'ultimo campo sia di larghezza variabile. Ciò si verifica quando l'ultima voce nella matrice è minore o uguale a 0.

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. Creare un nuovo TextFieldParser oggetto, definendo la larghezza e il formato.

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. Scorrere le righe, verificando il formato prima della lettura.

    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. Registra gli errori nella console.

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

Esempio

Di seguito è riportato l'esempio completo che legge dal file 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()

Programmazione efficiente

Le condizioni seguenti possono causare un'eccezione:

  • Non è possibile analizzare una riga usando il formato specificato (MalformedLineException). Il messaggio di eccezione specifica la riga che causa l'eccezione, mentre la ErrorLine proprietà viene assegnata al testo contenuto nella riga.
  • Il file specificato non esiste (FileNotFoundException).
  • Una situazione di attendibilità parziale in cui l'utente non dispone di autorizzazioni sufficienti per accedere al file. (SecurityException)
  • Il percorso è troppo lungo (PathTooLongException).
  • L'utente non dispone di autorizzazioni sufficienti per accedere al file (UnauthorizedAccessException).

Vedere anche