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

TextFieldParser 개체는 로그와 같은 구조적 텍스트 파일을 쉽고 효율적으로 구문 분석하는 방법을 제공합니다. TextFieldType 속성은 구분된 파일인지 또는 고정 너비 텍스트 필드가 있는 파일인지를 정의합니다.

쉼표로 구분된 텍스트 파일을 구문 분석하려면

  1. TextFieldParser를 만듭니다. 다음 코드는 MyReader라는 TextFieldParser를 만들고 test.txt 파일을 엽니다.

    Using MyReader As New Microsoft.VisualBasic.
                          FileIO.TextFieldParser(
                            "C:\TestFolder\test.txt")
    
  2. TextField 형식과 구분 기호를 정의합니다. 다음 코드는 TextFieldType 속성을 Delimited로, 구분 기호를 ","로 정의합니다.

    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
  3. 파일의 필드를 반복합니다. 손상된 줄이 있는 경우 오류를 보고하고 구문 분석을 계속합니다. 다음 코드는 파일을 반복하면서 각 필드를 차례로 표시하고 형식이 잘못된 필드를 모두 보고합니다.

    
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.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. End WhileEnd Using을 사용하여 WhileUsing 블록을 닫습니다.

        End While
    End Using
    

예시

이 예제에서는 test.txt 파일에서 읽습니다.

Using MyReader As New Microsoft.VisualBasic.
                      FileIO.TextFieldParser(
                        "C:\TestFolder\test.txt")
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.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

강력한 프로그래밍

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

  • 지정한 형식을 사용하여 행을 구문 분석할 수 없는 경우(MalformedLineException). 예외 메시지에는 예외를 발생시키는 줄이 지정되어 있지만 ErrorLine 속성은 해당 줄에 포함되어 있는 텍스트에 할당됩니다.

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

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

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

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

참고 항목