TextFieldParser オブジェクトは、ログなどの構造化テキスト ファイルを簡単かつ効率的に解析する方法を提供します。
PeekChars
メソッドを使用して複数の形式のファイルを処理し、ファイルを解析する際の各行の形式を決定できます。
複数の形式のテキスト ファイルを解析するには
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.
予期される形式と、エラーが報告されたときに使用される形式を定義します。 各配列の最後のエントリは -1 であるため、最後のフィールドは可変幅と見なされます。 これは、配列内の最後のエントリが 0 以下の場合に発生します。
Dim stdFormat As Integer() = {5, 10, 11, -1} Dim errorFormat As Integer() = {5, 5, -1}
幅と形式を定義して、新しい TextFieldParser オブジェクトを作成します。
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 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)。
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET