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

The code below 1Please ensure you test any script taken from my website on a test/development machine, before running on a production server. 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
            ' 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
        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.", _
            ' Close theOpenTextFieldParser
        End Try
    End While

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.