次の方法で共有


方法 : 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)。

参照

処理手順

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

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

関連項目

TextFieldParser

PeekChars

MalformedLineException

WriteAllText

EndOfData

TextFieldType

概念

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