HOW TO:在 Visual Basic 中從逗號分隔文字檔讀取
TextFieldParser 物件提供簡便且有效的方式來剖析結構化的文字檔,例如記錄檔。 TextFieldType 屬性 (Property) 會定義檔案是否為分隔的檔案,或是具有固定寬度文字欄位的檔案。
若要剖析以逗號分隔的文字檔
建立新的 TextFieldParser。 下列程式碼會建立名為 MyReader 的 TextFieldParser,並開啟檔案 test.txt。
Using MyReader As New Microsoft.VisualBasic. FileIO.TextFieldParser( "C:\TestFolder\test.txt")
定義 TextField 型別和分隔符號 (Delimiter)。 下列程式碼會將 TextFieldType 屬性定義為 Delimited,並將分隔符號定義為 ","。
MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",")
在檔案的欄位之間執行迴圈 (Loop)。 如果有任何一行損毀,即會報告錯誤並繼續剖析。 下列程式碼會在檔案之間執行迴圈,依序顯示每個欄位,並報告所有格式不正確的欄位。
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,以關閉 While 和 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)。
請參閱
工作
HOW TO:在 Visual Basic 中從固定寬度的文字檔讀取
HOW TO:在 Visual Basic 中以多種格式從文字檔讀取
疑難排解例外狀況:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
參考
Microsoft.VisualBasic.FileIO.TextFieldParser