TextFieldParser物件提供輕鬆且有效率地剖析結構化文本檔的方式,例如記錄檔。
屬性 TextFieldType 會定義剖析的檔案是分隔的檔案,還是具有固定寬度文字欄位的檔案。 在固定寬度文本檔中,結尾的欄位可以有可變寬度。 若要指定結尾的欄位具有可變寬度,請將它定義為寬度小於或等於零。
剖析固定寬度文本檔
請建立新的
TextFieldParser。 下列程式代碼會建立名為TextFieldParser的Reader,並開啟檔案test.log。Using Reader As New Microsoft.VisualBasic. FileIO.TextFieldParser("C:\TestFolder\test.log")將
TextFieldType屬性定義為FixedWidth,並定義寬度和格式。 下列程式代碼會定義文字的欄位;第一個欄位是 5 個字元寬、第二個欄位是 10 個字元寬、第三個欄位是 11 個字元寬,而第四個欄位是可變寬度。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使用
While和Using關閉End While和End 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
穩固程式設計
以下條件可能會造成例外狀況:
無法剖析資料列,因為無法使用指定的格式。MalformedLineException 例外狀況訊息會指定造成例外狀況的行,而 ErrorLine 屬性會指派給該行中包含的文字。
指定的檔案不存在 (FileNotFoundException)。
用戶沒有足夠的許可權存取檔案的部分信任狀況。 (SecurityException)。
路徑太長(PathTooLongException)。
用戶沒有足夠的許可權可存取檔案 (UnauthorizedAccessException)。