개체는 TextFieldParser
로그와 같은 구조화된 텍스트 파일을 쉽고 효율적으로 구문 분석하는 방법을 제공합니다.
이 속성은 TextFieldType
구문 분석된 파일이 구분된 파일인지 또는 텍스트의 고정 너비 필드가 있는 파일인지를 정의합니다. 고정 너비 텍스트 파일에서 끝의 필드에는 가변 너비가 있을 수 있습니다. 끝에 있는 필드의 너비가 가변이 되도록 지정하려면 너비가 0보다 작거나 같도록 정의합니다.
고정 너비 텍스트 파일을 구문 분석하려면
새
TextFieldParser
를 만듭니다. 다음 코드는TextFieldParser
을Reader
이라고 명명하고test.log
파일을 엽니다.Using Reader As New Microsoft.VisualBasic. FileIO.TextFieldParser("C:\TestFolder\test.log")
TextFieldType
속성을 너비와 형식을 정의하는 것으로FixedWidth
정의합니다. 다음 코드는 텍스트 열을 정의합니다. 첫 번째는 너비가 5자이고, 두 번째 10자, 세 번째 11자, 네 번째 문자는 가변 너비입니다.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
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
강력한 프로그래밍
다음 조건에서 예외가 발생합니다.
지정된 형식(MalformedLineException)을 사용하여 행을 구문 분석할 수 없습니다. 예외 메시지는 예외를 일으키는 줄을 지정하고 ErrorLine 속성은 줄에 포함된 텍스트에 할당됩니다.
지정한 파일이 없습니다(FileNotFoundException).
사용자에게 파일에 액세스할 수 있는 충분한 권한이 없는 부분 신뢰 상황입니다. (SecurityException).
경로가 너무 깁니다(PathTooLongException).
사용자에게 파일(UnauthorizedAccessException)에 액세스할 수 있는 충분한 권한이 없습니다.
참고하십시오
.NET