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

TextFieldParser オブジェクトには、構造化されたテキスト ファイル (ログなど) を簡単にかつ効率的に解析する方法が備わっています。

解析対象のファイルが区切り形式であるか固定幅フィールドであるかは、TextFieldType プロパティで定義します。 固定幅のテキスト ファイルでは、最終フィールドを可変幅とすることができます。 最後のフィールドを可変幅として指定するには、その幅に 0 以下の値を指定します。

固定幅のテキスト ファイルを解析するには

  1. 新しい TextFieldParser を作成します。 次のコードで Reader という名前の TextFieldParser を作成し、test.log ファイルを開きます。

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldType プロパティを FixedWidth として定義し、幅と形式を定義します。 次のコードでは、テキストの列を定義しています。先頭列の幅が 5 文字、2 列目が 10 文字、3 列目が 11 文字、そして 4 列目が可変幅です。

    Reader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. ファイル内のフィールドをループします。 破損している行が見つかった場合は、エラーを報告して解析を続行します。

    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.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.log ファイルから読み取りを行う例です。

Using Reader As New Microsoft.VisualBasic.FileIO.
   TextFieldParser("C:\TestFolder\test.log")

    Reader.TextFieldType =
       Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.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)。

関連項目