共用方式為


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

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

TextFieldType 屬性會定義剖析的檔是分隔檔還是文字欄位寬度固定的檔案。 在固定寬度文字檔中,結尾欄位可以有可變寬度。 若要指定結尾欄位是否有可變寬度,請將其寬度定義為小於或等於零。

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

  1. 建立新的 TextFieldParser。 下列程式碼會建立名為 Reader 的 TextFieldParser,並開啟檔案 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 While 和 End Using,以關閉 While 和 Using 區塊。

       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

穩固程式設計

以下條件可能會造成例外狀況:

請參閱

工作

HOW TO:在 Visual Basic 中從逗號分隔文字檔讀取

HOW TO:在 Visual Basic 中以多種格式從文字檔讀取

逐步解說:在 Visual Basic 中管理檔案和目錄

疑難排解:讀取和寫入文字檔 (Visual Basic)

疑難排解例外狀況:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException

參考

Microsoft.VisualBasic.FileIO.TextFieldParser

概念

使用 TextFieldParser 物件剖析文字檔 (Visual Basic)

變更記錄

日期

記錄

原因

2011 年 1 月

加入有關可變寬度欄位的資訊。

客戶回函。