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

更新 : 2007 年 11 月

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 While と End Using で閉じます。

       End While
    End Using
    

使用例

この例では、test.txt ファイルを読み取ります。

Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.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

堅牢性の高いプログラム

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

参照

処理手順

方法 : Visual Basic で固定幅のテキスト ファイルを読み取る

方法 : Visual Basic で複数の書式を持つテキスト ファイルを読み取る

チュートリアル : Visual Basic によるファイルとディレクトリの操作

トラブルシューティング : テキスト ファイルの読み取りと書き込み

例外のトラブルシューティング : Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException

概念

TextFieldParser オブジェクトによるテキスト ファイルの解析

参照

TextFieldParser オブジェクト