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

更新 : 2007 年 11 月

TextFieldParser オブジェクトを使用すると、ログなどの構造化されたテキスト ファイルを簡単かつ効率的に解析できます。

区切り記号が使用されたファイルと固定幅のテキスト フィールドを持つファイルのどちらであるかは、TextFieldType プロパティで定義します。固定幅のファイル内で可変幅のフィールドを指定するには、フィールド幅を -1 として定義します。

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

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

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

    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 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

堅牢性の高いプログラム

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

参照

処理手順

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

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

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

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

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

概念

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

参照

TextFieldParser オブジェクト