TextFieldParser
オブジェクトは、ログなどの構造化テキスト ファイルを簡単かつ効率的に解析する方法を提供します。
TextFieldType
プロパティは、区切りファイルか、固定幅のテキスト フィールドを持つファイルかを定義します。
コンマ区切りテキスト ファイルを解析するには
新しい
TextFieldParser
を作成します。 次のコードは、TextFieldParser
という名前のMyReader
を作成し、ファイルtest.txt
を開きます。Using MyReader As New Microsoft.VisualBasic. FileIO.TextFieldParser( "C:\TestFolder\test.txt")
TextField
の型と区切り記号を定義します。 次のコードでは、TextFieldType
プロパティをDelimited
として定義し、区切り記号を "," として定義します。MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",")
ファイル内のフィールドをループ処理します。 いずれかの行が破損している場合は、エラーを報告し、解析を続行します。 次のコードは、ファイルをループ処理し、各フィールドを順番に表示し、正しく書式設定されていないフィールドを報告します。
Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.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
While
とUsing
を使用して、End While
ブロックとEnd Using
ブロックを閉じます。End While End Using
例
この例では、ファイル test.txt
から読み取ります。
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.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)。
こちらも参照ください
.NET