개체는 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에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET