共用方式為


如何:從 Visual Basic 中的固定寬度文本檔讀取

TextFieldParser物件提供輕鬆且有效率地剖析結構化文本檔的方式,例如記錄檔。

屬性 TextFieldType 會定義剖析的檔案是分隔的檔案,還是具有固定寬度文字欄位的檔案。 在固定寬度文本檔中,結尾的欄位可以有可變寬度。 若要指定結尾的欄位具有可變寬度,請將它定義為寬度小於或等於零。

剖析固定寬度文本檔

  1. 請建立新的 TextFieldParser。 下列程式代碼會建立名為 TextFieldParserReader ,並開啟檔案 test.log

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldType 屬性定義為 FixedWidth,並定義寬度和格式。 下列程式代碼會定義文字的欄位;第一個欄位是 5 個字元寬、第二個欄位是 10 個字元寬、第三個欄位是 11 個字元寬,而第四個欄位是可變寬度。

    Reader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. 遍歷檔案中的每個欄位。 如果有任何行損壞,請報告錯誤並繼續解析。

    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    
  4. 使用WhileUsing關閉End WhileEnd Using區塊。

        End While
    End Using
    

範例

這個範例會從檔案 test.log讀取 。

Using Reader As New Microsoft.VisualBasic.FileIO.
   TextFieldParser("C:\TestFolder\test.log")

    Reader.TextFieldType =
       Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
End Using

穩固程式設計

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

另請參閱