共用方式為


HOW TO:在 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. 對資料列進行迴圈 (Loop),在讀取之前先測試格式。

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

          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()

穩固程式設計

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

請參閱

工作

HOW TO:在 Visual Basic 中從逗號分隔文字檔讀取

HOW TO:在 Visual Basic 中從固定寬度的文字檔讀取

參考

Microsoft.VisualBasic.FileIO.TextFieldParser

PeekChars

MalformedLineException

WriteAllText

EndOfData

TextFieldType

概念

使用 TextFieldParser 物件剖析文字檔 (Visual Basic)

變更記錄

日期

記錄

原因

2011 年 1 月

加入有關可變寬度欄位的資訊。

客戶回函。