Share via


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

업데이트: 2007년 11월

TextFieldParser 개체를 사용하면 로그와 같은 구조화된 텍스트 파일을 쉽게 효과적으로 구문 분석할 수 있습니다. PeekChars 메서드를 사용하여 파일을 구문 분석하면서 각 줄의 형식을 확인함으로써 여러 형식이 포함된 파일을 처리할 수 있습니다.

여러 형식의 텍스트 파일을 구문 분석하려면

  1. 예상 형식과 오류가 보고될 때 사용되는 형식을 정의합니다.

    Dim StdFormat As Integer()= {5,10,11,-1}
    Dim ErrorFormat As Integer() = {5,5,-1}
    
  2. 너비와 형식을 정의하여 새 TextFieldParser 개체를 만듭니다.

    Using MyReader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    
  3. 행을 순환하며 검색하여 읽기 전에 형식을 테스트합니다.

    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
    
  4. 콘솔에 오류를 씁니다.

          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

강력한 프로그래밍

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

참고 항목

작업

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

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

개념

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

참조

TextFieldParser 개체

TextFieldParser.PeekChars 메서드

MalformedLineException

My.Computer.FileSystem.WriteAllText 메서드

TextFieldParser.EndOfData 속성

TextFieldParser.TextFieldType 속성