다음을 통해 공유


방법: 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()

강력한 프로그래밍

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

참고하십시오