다음을 통해 공유


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

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

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

  1. TextFieldParser를 만듭니다. 다음 코드는 TextFieldParserMyReader이라고 명명하고 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. WhileUsing 블록을 End WhileEnd Using를 사용하여 닫습니다.

        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)에 액세스할 수 있는 충분한 권한이 없습니다.

참고하십시오