다음을 통해 공유


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

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

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

  1. testfile.txt 텍스트 파일을 프로젝트에 추가합니다. 텍스트 파일에 다음 내용을 추가합니다.

    Err  1001 Cannot access resource.
    Err  2014 Resource not found.
    Acc  10/03/2009User1      Administrator.
    Err  0323 Warning: Invalid access attempt.
    Acc  10/03/2009User2      Standard user.
    Acc  10/04/2009User2      Standard user.
    
  2. 예상 형식과 오류가 보고될 때 사용되는 형식을 정의합니다. 각 배열의 마지막 항목이 -1이므로 마지막 필드는 가변 너비 필드로 간주됩니다. 이는 배열의 마지막 항목이 0보다 작거나 같을 때 발생합니다.

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

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

    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try 
            Dim rowType = 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)
            Else 
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
    
  5. 콘솔에 오류를 씁니다.

          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 FileIO.TextFieldParser("..\..\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = stdFormat
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try 
            Dim rowType = 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)
            Else 
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
        Catch ex As FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try 
    End While 
End Using
Console.ReadLine()

강력한 프로그래밍

다음 조건에서 예외가 발생할 수 있습니다.

  • 지정된 형식을 사용하여 행을 구문 분석할 수 없는 경우(MalformedLineException). 예외 메시지에 예외의 원인이 된 줄이 표시되고 줄에 포함된 텍스트에 ErrorLine 속성이 할당됩니다.

  • 지정된 파일이 없는 경우(FileNotFoundException)

  • 사용자에게 파일에 액세스할 수 있는 충분한 권한이 없는 부분 신뢰 상황인 경우 (SecurityException).

  • 경로가 너무 긴 경우(PathTooLongException)

  • 파일에 액세스할 수 있는 충분한 권한이 사용자에게 없는 경우(UnauthorizedAccessException)

참고 항목

작업

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

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

참조

TextFieldParser

PeekChars

MalformedLineException

WriteAllText

EndOfData

TextFieldType

개념

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