다음을 통해 공유


방법: Visual Basic의 고정 너비 텍스트 파일에서 읽기

개체는 TextFieldParser 로그와 같은 구조화된 텍스트 파일을 쉽고 효율적으로 구문 분석하는 방법을 제공합니다.

이 속성은 TextFieldType 구문 분석된 파일이 구분된 파일인지 또는 텍스트의 고정 너비 필드가 있는 파일인지를 정의합니다. 고정 너비 텍스트 파일에서 끝의 필드에는 가변 너비가 있을 수 있습니다. 끝에 있는 필드의 너비가 가변이 되도록 지정하려면 너비가 0보다 작거나 같도록 정의합니다.

고정 너비 텍스트 파일을 구문 분석하려면

  1. TextFieldParser를 만듭니다. 다음 코드는 TextFieldParserReader이라고 명명하고 test.log 파일을 엽니다.

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldType 속성을 너비와 형식을 정의하는 것으로 FixedWidth정의합니다. 다음 코드는 텍스트 열을 정의합니다. 첫 번째는 너비가 5자이고, 두 번째 10자, 세 번째 11자, 네 번째 문자는 가변 너비입니다.

    Reader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. 파일에서 필드를 순회합니다. 줄이 손상된 경우 오류를 보고하고 구문 분석을 계속합니다.

    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
    
  4. WhileUsing 블록을 End WhileEnd 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

강력한 프로그래밍

다음 조건에서 예외가 발생합니다.

참고하십시오