次の方法で共有


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

TextFieldParser オブジェクトは、ログなどの構造化テキスト ファイルを簡単かつ効率的に解析する方法を提供します。 TextFieldType プロパティは、区切りファイルか、固定幅のテキスト フィールドを持つファイルかを定義します。

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

  1. 新しい TextFieldParser を作成します。 次のコードは、TextFieldParserという名前のMyReaderを作成し、ファイル 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 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)。

こちらも参照ください