Minying's Blog

Just another WordPress.com weblog

在 Visual Basic 中從固定寬度的文字檔讀取

Posted by minying 於 1 十二月, 2008

TextFieldParser 物件提供簡便且有效的方式來剖析結構化的文字檔,例如記錄檔。

TextFieldType 屬性 (Property) 會定義檔案是否為分隔的檔案,或是具有固定寬度文字欄位的檔案。若要在固定寬度的檔案中指定可變動寬度的欄位,請將欄位寬度定義為 -1。

若要剖析固定寬度的文字檔

  1. 建立新的 TextFieldParser。下列程式碼會建立名為 ReaderTextFieldParser,並且開啟檔案 test.log
       
    Using Reader As New _ Microsoft.VisualBasic.FileIO.TextFieldParser _ (“C:\TestFolder\test.log")

     

  2. TextFieldType 屬性定義為 FixedWidth,並定義寬度和格式。下列程式碼會定義文字的資料行:第一個資料行為 5 個字元寬、第二個為 10 個字元寬、第三個為 11 個字元寬,而第四個資料行的寬度是可變動的。
       
    Reader.TextFieldType = _
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)

     

  3. 在檔案的欄位之間執行迴圈 (Loop)。若有任何一行毀損,則報告錯誤並繼續剖析。
       
    Dim currentRow As String()

       While Not Reader.EndOfData
          Try
             currentRow = Reader.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.log

   
Using Reader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser(“C:\TestFolder\test.log")
   Reader.TextFieldType = _
   Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
   Reader.SetFieldWidths(5, 10, 11, -1)
   Dim currentRow As String()
   While Not Reader.EndOfData
      Try
         currentRow = Reader.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

 

發表留言