We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

TextFieldParser and Reading in text file data - Problems...

Medium Priority
1,462 Views
Last Modified: 2013-12-25
Hello,
     I am somewhat new to .NET stuff.   I am an old VB v3 to v6 guy, so bare with me.
I am just trying to do a simple opening and reading of a text file.  The file is comma delimited.
I am trying to not using the old VB way of doing this, IE Open file for output as #1...  
I am trying to using the textfieldparser object.   It seems to be a good new way to go, it works on my first pass through my code, but when it loops around, it doesn't grab the next line in the text file.

I have a text file that is comma delimited and has a carriage return at the end of each line.  

When I was debugging it, I put a put a iMyLineCnt =  theTextFieldParser.LineNumber before the While loop starts and it return the number of lines in my file.. I put LineNumber after the  currentRow = theTextFieldParser.ReadFields (Which is in the while loop) and it loses count and goes to a -1.

Please help...Thanks...


The text file looks like this

6/17/2007,Smtih,Dan,1,1,2,2,0,AMERICAN WIGEON,4,BRANT,2,CANADA GOOSE,1,CANVASBACK,2
7/9/2007,Brown,Jim,1,1,7,2,0,AMERICAN WIGEON,4,BRANT,1

THanks in advance...

'
        Dim theTextFieldParser As FileIO.TextFieldParser


        theTextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(txtPath.Text)

        ' Set TextFieldParser object's TextFieldType property to Delimited.
        theTextFieldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited

        ' Configure delimiters to handle a comma delimited text file:
        ' Set TextFieldParser object's Delimiter's property to a string array
        ' containing one element with the value ",".
        theTextFieldParser.Delimiters = New String() {","}

        Dim iMyCNT As Integer
        Dim a As Integer


        ' Declare a variable named currentRow of type string array.
        Dim currentRow() As String


        While Not theTextFieldParser.EndOfData
            Try
                ' Read the fields on the current line
                ' and assign them to the currentRow array variable.
                currentRow = theTextFieldParser.ReadFields

                ' Declare a variable named currentField of type String.
                Dim currentField As String

                ' Use the currentField variable to loop
                ' through fields in the currentRow.

                For Each currentField In currentRow
                    i += 1
                    If i = 1 Then
                        dtReportDate = CDate(currentField)
                    ElseIf i = 2 Then
                        sLastName = currentField
                    ElseIf i = 3 Then
                        sFirstName = currentField
                    ElseIf i = 4 Then
                        iHunters = Convert.ToInt32(currentField)
                    ElseIf i = 5 Then
                        iCars = Convert.ToInt32(currentField)
                    ElseIf i = 6 Then
                        iHours = Convert.ToInt32(currentField)
                    ElseIf i = 7 Then
                        iArea = Convert.ToInt32(currentField)
                    ElseIf i = 8 Then
                        iBlind = Convert.ToInt32(currentField)
                    ElseIf i >= 9 Then
                        j += 1
                        If j = 1 Then
                            sSpeciesName = currentField
                        Else
                            iHarvested = Convert.ToInt32(currentField)
                           j = 0
                        End If
                    End If
                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
                ' If successful or if an exception is thrown,
                ' close the TextFieldParser.
                theTextFieldParser.Close()
                Conn.Close()
            End Try
        End While
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
Does the CSV file have quotes around the strings?

    theTextFieldParser.HasFieldsEnclosedInQuotes = True

Bob

Author

Commented:
No... it is the text file looks exacts the way I cut and pasted it into the question?

When I step through the code, on the first run through it, it works, but when it reaches the end of the code, instead of looping and grabbing the next line for processing, it jumps out of the loop.

Are you saying I should set the hasfieldenclosedinQuotes = false to just make sure???  

I would think if it wasn't working, it wouldn't even go through the first pass and process the first line.

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
Can you upload the file to http://www.ee-stuff.com?

Bob
Top Expert 2007

Commented:
It's because you are closing your TextFieldParser.  

            Finally
                ' If successful or if an exception is thrown,
                ' close the TextFieldParser.
                'theTextFieldParser.Close()    '<  REMOVE THIS LINE
                'Conn.Close()    ''<  REMOVE THIS LINE
            End Try
        End While

               ' MOVE THESE LINES HERE
                theTextFieldParser.Close()    '<  REMOVE THIS LINE
                Conn.Close()    ''<  REMOVE THIS LINE

Author

Commented:
Let me try VBRocks suggestion, he might have nailed this.  

I am going to kick myself if that is what it is....

Top Expert 2007
Commented:
Should be like this:

        Dim theTextFieldParser As FileIO.TextFieldParser
        theTextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(txtPath.Text)

        theTextFieldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited

        theTextFieldParser.Delimiters = New String() {","}


        While Not theTextFieldParser.EndOfData
            Try
                ' Read the fields on the current line
                ' and assign them to the currentRow array variable.
                currentRow = theTextFieldParser.ReadFields

                ' Declare a variable named currentField of type String.
                Dim currentField As String

                ' Use the currentField variable to loop
                ' through fields in the currentRow.

                For Each currentField In currentRow
                    i += 1
                    If i = 1 Then
                        dtReportDate = CDate(currentField)
                    ElseIf i = 2 Then
                        sLastName = currentField
                    ElseIf i = 3 Then
                        sFirstName = currentField
                    ElseIf i = 4 Then
                        iHunters = Convert.ToInt32(currentField)
                    ElseIf i = 5 Then
                        iCars = Convert.ToInt32(currentField)
                    ElseIf i = 6 Then
                        iHours = Convert.ToInt32(currentField)
                    ElseIf i = 7 Then
                        iArea = Convert.ToInt32(currentField)
                    ElseIf i = 8 Then
                        iBlind = Convert.ToInt32(currentField)
                    ElseIf i >= 9 Then
                        j += 1
                        If j = 1 Then
                            sSpeciesName = currentField
                        Else
                            iHarvested = Convert.ToInt32(currentField)
                            j = 0
                        End If
                    End If
                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

            End Try

        End While

        ' If successful or if an exception is thrown,
        ' close the TextFieldParser.
        theTextFieldParser.Close()
        Conn.Close()

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
VBROCKS!!!!  YOU ARE THE STUD OR STUDETTE....   THANKS A BUNCH.

I am new to dot NET...  I have only been messing with dot NET for a few months.  I am suppose to go to training for intro to dot net in Aug. so hopefully that will help.  I am not used to the TRY, Catch, etc...  error handling ... it is all new to me.

Thanks again.   I appreicate your help.  I messed with this for a couple of hours yesterday, even having other developers look at my code.  

I love this website...  it always gets me to the next step when I get stuck.


Thanks again.

 
Top Expert 2007

Commented:
Stud.  :)  - (Thank you, by the way)

You know, I think you're really going to like VB.NET 2005.  I still do VB6 programming, and .NET blows it
away!

If your interested, a VERY good book to help you get rolling with VB.NET is "Visual Basic .NET
Step By Step", written by Michael Halvorson.  I've read the book myself, and really enjoyed it!  It's a
great introductory book for the VB.NET and the .NET Framework.  I have recommended it to quite a few
other friends and co-workers.  You can pick up a used .NET 2003 version book for under 5 bucks at
Amazon.com.  You can pick up a new or used .NET 2005 version for around 25 bucks at Amazon as
well.

Another very good book to consider after the step by step book is, "OOP with Microsoft Visual
Basic .NET... Step By Step", written by Robin A. Reynolds-Haertle.  The .NET Framework is entirely
Object-Oriented, so a good understanding of OOP (Object-Oriented Programming) concepts is essential.

Good luck!

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.