操作說明:在 Visual Basic 中以多種格式從文字檔讀取

TextFieldParser 物件可讓您輕鬆有效率地剖析結構化文字檔,例如記錄檔。 您可以使用 PeekChars 方法來處理具有多種格式的檔案,以在剖析整個檔案時判斷每行格式。

剖析具有多種格式的文字檔

  1. 將名為 testfile.txt 的文字檔新增至專案。 將下列內容新增至文字檔:

    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. 定義預期的格式,以及回報錯誤時所使用的格式。 每個陣列中的最後一個項目為 -1,因此將最後一個欄位假設為可變寬度。 陣列中的最後一個項目小於或等於 0 時會發生這種情況。

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. 建立新的 TextFieldParser 物件,並定義寬度和格式。

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. 反覆執行資料列,並在讀取之前測試格式。

    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. 將錯誤寫入主控台。

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

範例

以下為從 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()

穩固程式設計

以下條件可能會造成例外狀況:

另請參閱