TextFieldParser物件提供輕鬆且有效率地剖析結構化文本檔的方式,例如記錄檔。 屬性 TextFieldType 會定義它是分隔的檔案,還是具有固定寬度文字欄位的檔案。
剖析逗號分隔文字檔
請建立新的
TextFieldParser。 下列程式代碼會建立名為TextFieldParser的MyReader,並開啟檔案test.txt。Using MyReader As New Microsoft.VisualBasic. FileIO.TextFieldParser( "C:\TestFolder\test.txt")TextField定義類型和分隔符。 下列程式代碼會將TextFieldType屬性Delimited定義為 ,並將分隔符定義為 “,”。MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",")遍歷檔案中的每個欄位。 如果有任何行損毀,請報告錯誤並繼續解析。 下列程式代碼會迴圈查看檔案,並接著顯示每個欄位,並報告任何格式不正確的欄位。
Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.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.txt讀取 。
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.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)。