次の方法で共有


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

TextFieldParser オブジェクトは、ログなどの構造化テキスト ファイルを簡単かつ効率的に解析する方法を提供します。

TextFieldType プロパティは、解析されたファイルが区切りファイルであるか、固定幅のテキスト フィールドを持つファイルであるかを定義します。 固定幅のテキスト ファイルでは、末尾のフィールドの幅を可変にすることができます。 末尾のフィールドの幅が可変になるように指定するには、幅が 0 以下になるように定義します。

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

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

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldTypeプロパティをFixedWidthとして定義し、幅と形式を定義します。 次のコードは、テキストの列を定義します。1 つ目は幅が 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. WhileUsingを使用して、End WhileブロックとEnd 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)。

こちらも参照ください