共用方式為


如何:從 Visual Basic 中的逗號分隔文本文件讀取

TextFieldParser物件提供輕鬆且有效率地剖析結構化文本檔的方式,例如記錄檔。 屬性 TextFieldType 會定義它是分隔的檔案,還是具有固定寬度文字欄位的檔案。

剖析逗號分隔文字檔

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

    Using MyReader As New Microsoft.VisualBasic.
                          FileIO.TextFieldParser(
                            "C:\TestFolder\test.txt")
    
  2. TextField定義類型和分隔符。 下列程式代碼會將 TextFieldType 屬性 Delimited 定義為 ,並將分隔符定義為 “,”。

    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
  3. 遍歷檔案中的每個欄位。 如果有任何行損毀,請報告錯誤並繼續解析。 下列程式代碼會迴圈查看檔案,並接著顯示每個欄位,並報告任何格式不正確的欄位。

    
    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
    
  4. 使用WhileUsing關閉End WhileEnd 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

穩固程式設計

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

另請參閱