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

TextFieldParser オブジェクトには、構造化されたテキスト ファイル (ログなど) を簡単にかつ効率的に解析する方法が備わっています。 PeekChars メソッドを使用して、ファイルを解析するときに各行の書式を判断すると、複数の書式を持つファイルを処理できます。

複数の書式を持つテキスト ファイルを解析するには

  1. testfile.txt という名前のテキスト ファイルをプロジェクトに追加します。 次の内容をテキスト ファイルに追加します。

    Err  1001 Cannot access resource.
    Err  2014 Resource not found.
    Acc  10/03/2009User1      Administrator.
    Err  0323 Warning: Invalid access attempt.
    Acc  10/03/2009User2      Standard user.
    Acc  10/04/2009User2      Standard user.
    
  2. 予期される形式と、エラーが報告されたときに使用される形式を定義します。 各配列の最後のエントリは -1 です。そのため、最後のフィールドは可変幅であると見なされます。 これは、配列の最後のエントリが 0 以下の場合に発生します。

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. 新しい TextFieldParser オブジェクトを作成し、幅と形式を定義します。

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. 各行をループし、読み取り前に書式を調べます。

    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = MyReader.PeekChars(3)
            If String.Compare(rowType, "Err") = 0 Then
                ' If this line describes an error, the format of the row will be different.
                MyReader.SetFieldWidths(errorFormat)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
    
  5. エラーをコンソールに書き込みます。

            Catch ex As Microsoft.VisualBasic.
                          FileIO.MalformedLineException
                MsgBox("Line " & ex.Message & " is invalid.")
            End Try
        End While
    End Using
    

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

Dim stdFormat As Integer() = {5, 10, 11, -1}
Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = stdFormat
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = MyReader.PeekChars(3)
            If String.Compare(rowType, "Err") = 0 Then
                ' If this line describes an error, the format of the row will be different.
                MyReader.SetFieldWidths(errorFormat)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
        Catch ex As FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
    End While
End Using
Console.ReadLine()

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

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

  • 指定された形式で行を解析できない (MalformedLineException)。 例外の原因となった行が例外メッセージで報告され、その行に含まれているテキストには ErrorLine プロパティが代入されます。
  • 指定されたファイルが存在しない (FileNotFoundException)。
  • 部分信頼の状況下で、ファイルにアクセスするために必要なアクセス許可がユーザーにない。 (SecurityException)。
  • パスが長すぎる (PathTooLongException)。
  • ファイルにアクセスする十分なアクセス許可がユーザーにない (UnauthorizedAccessException)。

関連項目