VB: Retrieve the header row column names from a text file

The code below 1 is an example of how to retrieve the column/field names from the header row from a text file, and add them to a “ListBox”.

    Dim tfp As Microsoft.VisualBasic.FileIO.TextFieldParser
    ' Change "Filename.TXT" to the filename of your choice
    tfp = My.Computer.FileSystem.OpenTextFieldParser("Filename.TXT")
    ' Identify the file type as Delimited
    tfp.TextFieldType = FileIO.FieldType.Delimited

    ' Set the delimiter of the file.  In this example comma.
    tfp.Delimiters = New String() {","}
    ' To set the delimiter to the pipe system, use:
    '    tfp.Delimiters = New String() {"|"}
    ' or, for the Tab character, use:
    '    tfp.Delimiters = New String() {vbTab}

    ' Does the file use quotes to enclose text values?
    tfp.HasFieldsEnclosedInQuotes = True

    ' Declare a variable to store the current row
    Dim cr() As String

    ' Loop through the lines within the file
    While Not tfp.EndOfData
        Try
            ' Get the currentrow, and read the fields
            cr = tfp.ReadFields
            ' Declare a variable to store the current field
            Dim cf As String
            ' Loop through each field within the current row
            For Each cf In cr
                ListBox.Items.Add(cf.ToString)
             Next
        Catch malFormLineEx As Microsoft.VisualBasic.FileIO.MalformedLineException
            MessageBox.Show("Line " & malFormLineEx.Message & _
                            "is not valid and will be skipped.", _
                            "Malformed Line Exception")
        Catch ex As Exception
            MessageBox.Show(ex.Message & " exception has occurred.", _
                            "Exception")
        Finally
            ' Close theOpenTextFieldParser
            tfp.Close()
        End Try
    End While
  1. Please ensure you test any script taken from my website on a test/development machine, before running on a production server.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.