方法: Visual Basic でコンマ区切りのテキスト ファイルを読み取る

TextFieldParser オブジェクトには、構造化されたテキスト ファイル (ログなど) を簡単にかつ効率的に解析する方法が備わっています。 区切り形式のファイルか、固定幅フィールドのテキストを使用したファイルかは、TextFieldType プロパティで定義します。

コンマ区切りテキスト ファイルを解析するには

  1. 新しい TextFieldParser を作成します。 次のコードで MyReader という名前の TextFieldParser を作成し、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. While ブロックと Using ブロックをそれぞれ 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

信頼性の高いプログラミング

次の条件を満たす場合は、例外が発生する可能性があります。

  • 指定された形式で行を解析できない (MalformedLineException)。 例外の原因となった行が例外メッセージで報告され、その行に含まれているテキストには ErrorLine プロパティが代入されます。

  • 指定されたファイルが存在しない (FileNotFoundException)。

  • 部分信頼の状況下で、ファイルにアクセスするために必要なアクセス許可がユーザーにない。 (SecurityException)。

  • パスが長すぎる (PathTooLongException)。

  • ファイルにアクセスする十分なアクセス許可がユーザーにない (UnauthorizedAccessException)。

関連項目