共用方式為


如何:在 Visual Basic 中從逗號分隔文字檔讀取

TextFieldParser 物件可讓您輕鬆有效率地剖析結構化文字檔,例如記錄檔。 TextFieldType 屬性會定義檔案是有分隔符號的檔案,還是具有固定寬度文字欄位的檔案。

剖析逗號分隔文字檔

  1. 建立新的 TextFieldParser。 下列程式碼會建立名為 MyReaderTextFieldParser,並開啟檔案 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. 使用 End WhileEnd Using 關閉 WhileUsing 區塊。

        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

穩固程式設計

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

另請參閱