Share via


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

업데이트: 2007년 11월

TextFieldParser 개체를 사용하면 로그와 같은 구조화된 텍스트 파일을 쉽게 효과적으로 구문 분석할 수 있습니다.

TextFieldType 속성은 파일이 구분된 파일인지 텍스트가 고정 너비 필드인 파일인지를 정의합니다. 고정 너비 파일에서 가변 너비 필드를 지정하려면 필드 너비를 -1로 정의합니다.

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

  1. 새 TextFieldParser를 만듭니다. 다음 코드에서는 Reader라는 이름의 TextFieldParser를 만들고 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. 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

강력한 프로그래밍

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

참고 항목

작업

방법: Visual Basic에서 쉼표로 구분된 텍스트 파일 읽기

방법: Visual Basic에서 여러 형식의 텍스트 파일 읽기

연습: Visual Basic에서 파일과 디렉터리 조작

문제 해결: 텍스트 파일 읽기 및 쓰기

예외 문제 해결: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException

개념

TextFieldParser 개체를 사용하여 텍스트 파일 구문 분석

참조

TextFieldParser 개체