방법: Visual Basic에서 여러 형식의 텍스트 파일 읽기
업데이트: 2007년 11월
TextFieldParser 개체를 사용하면 로그와 같은 구조화된 텍스트 파일을 쉽게 효과적으로 구문 분석할 수 있습니다. PeekChars 메서드를 사용하여 파일을 구문 분석하면서 각 줄의 형식을 확인함으로써 여러 형식이 포함된 파일을 처리할 수 있습니다.
여러 형식의 텍스트 파일을 구문 분석하려면
예상 형식과 오류가 보고될 때 사용되는 형식을 정의합니다.
Dim StdFormat As Integer()= {5,10,11,-1} Dim ErrorFormat As Integer() = {5,5,-1}
너비와 형식을 정의하여 새 TextFieldParser 개체를 만듭니다.
Using MyReader As New _ Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth
행을 순환하며 검색하여 읽기 전에 형식을 테스트합니다.
Dim CurrentRow As String() While Not MyReader.EndOfData Try Dim RowType As String = 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) CurrentRow = MyReader.ReadFields MyReader.SetFieldWidths(StdFormat) Else 'Otherwise parse the fields normally CurrentRow = MyReader.ReadFields For Each newString As String In CurrentRow My.Computer.FileSystem.WriteAllText _ ("newFile.txt", newString, True) Next End If
콘솔에 오류를 씁니다.
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 _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = 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)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
강력한 프로그래밍
다음 조건에서 예외가 발생합니다.
지정된 형식을 사용하여 행을 구문 분석할 수 없는 경우(MalformedLineException). 예외 메시지에 예외의 원인이 된 줄이 표시되고 줄에 포함된 텍스트에 TextFieldParser.ErrorLine 속성이 할당됩니다.
지정된 파일이 없는 경우(FileNotFoundException)
사용자에게 파일에 액세스할 수 있는 충분한 권한이 없는 부분 신뢰 상황인 경우(SecurityException)
경로가 너무 긴 경우(PathTooLongException)
파일에 액세스할 수 있는 충분한 권한이 사용자에게 없는 경우(UnauthorizedAccessException)
참고 항목
작업
방법: Visual Basic에서 쉼표로 구분된 텍스트 파일 읽기
방법: Visual Basic에서 고정 너비 텍스트 파일 읽기
개념
TextFieldParser 개체를 사용하여 텍스트 파일 구문 분석