vb.net reading CSV file - null exception

Hello Experts
I am trying to parse CSV file which has 2 rows of data, its reading the first line correctly, storing in the structure variable but when I loop it through the second time, it errors when I try to read the first column (fields(0))

"Object reference not set to an instance of an object."

please can someone advice what is wrong with this code?

  Private Function ParseCSVs() As Boolean

        Dim LocalFilePath As String = String.Empty

        For Each aCSV As xCSV In _CSVs
            LocalFilePath = My.Settings.Item("GRFiles") & "DailyOrders\" & aCSV.CSVFileName
        
            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(LocalFilePath)

                MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
                MyReader.Delimiters = New String() {","}  '{vbTab}
                Dim currentRow As String()
                'Loop through all of the fields in the file.  
                'If any lines are corrupt, report an error and continue parsing.  
                Dim OrderRequest As New cCSVOrderRequest
                OrderRequest.Items = New List(Of cCSVProductItem)

                Dim Product As ProductClass = Nothing
                Dim Item As cCSVProductItem = Nothing
                While Not MyReader.EndOfData
                    Try

                        currentRow = MyReader.ReadFields()
                        ' Include code here to handle the row. 
                        Dim fields As String() = MyReader.ReadFields()
                        Item = New cCSVProductItem()
                        Item.OrderItemNumber = fields(0)
                        Item.PartNumber = fields(2)
                        Item.Description = fields(3)
                        Item.Quantity = fields(4)
                        Item.ShipTitle = fields(17)
                        Item.ShipToName = fields(18)
                        Item.ShipAddress1 = fields(19)
                        Item.ShipAddress2 = fields(20)
                        Item.ShipAddress3 = fields(21)
                        Item.ShipAddress4 = fields(22)
                        If fields(23).Contains("GB") Then
                            Item.ShipCountry = "238"
                        Else
                            Item.ShipCountry = ""
                            'CommonFunctions.SendErrorEmail("")
                        End If
                        Item.ShipPostCode = fields(24)
                        Item.PhoneNumber = fields(28)
                        OrderRequest.Items.Add(Item)
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        'CommonFunctions.SendErrorEmail("")
                        Return False
                    End Try
                End While
                aCSV.OrderRequest = OrderRequest
            End Using
        Next
        Return True
    End Function

Open in new window

Untitled.png
mehmastAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
That is because you are reading both rows in the first pass and therefore when you try to get the next row there is no more data, fields(0) is null and you are trying to assign that to a variable in this line of code.

 Item.OrderItemNumber = fields(0)

This is where you are reading in both lines in the file in the first pass. Modify the code to read once per pass.

Try
    '' First time you read the line from the file
    currentRow = MyReader.ReadFields()
    ' Include code here to handle the row. 
    
    '' Now you fread the second line in from the file 
    Dim fields As String() = MyReader.ReadFields()

Open in new window

0
mehmastAuthor Commented:
Hello
thank you for picking this up for me
i have headers in first row, so this line will ignore the headers
currentRow = MyReader.ReadFields()

the second and the third rows has data which I want to extract,

how can i make sure i only run the headers once in the loop? please advice
0
john hillceoCommented:
something like this?


 Private Function ParseCSVs() As Boolean

        Dim LocalFilePath As String = String.Empty

        For Each aCSV As xCSV In _CSVs
            LocalFilePath = My.Settings.Item("GRFiles") & "DailyOrders\" & aCSV.CSVFileName
        
            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(LocalFilePath)

                MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
                MyReader.Delimiters = New String() {","}  '{vbTab}
                Dim currentRow As String()
                'Loop through all of the fields in the file.  
                'If any lines are corrupt, report an error and continue parsing.  
                Dim OrderRequest As New cCSVOrderRequest
                OrderRequest.Items = New List(Of cCSVProductItem)

                Dim Product As ProductClass = Nothing
                Dim Item As cCSVProductItem = Nothing
  Dim Cntr As Integer = 1
                While Not MyReader.EndOfData
                    Try

                      If Cntr = 1 Then
                            currentRow = MyReader.ReadFields()
                        End If
                        ' Include code here to handle the row. 
                        Dim fields As String() = MyReader.ReadFields()
                        Item = New cCSVProductItem()
                        Item.OrderItemNumber = fields(0)
                        Item.PartNumber = fields(2)
                        Item.Description = fields(3)
                        Item.Quantity = fields(4)
                        Item.ShipTitle = fields(17)
                        Item.ShipToName = fields(18)
                        Item.ShipAddress1 = fields(19)
                        Item.ShipAddress2 = fields(20)
                        Item.ShipAddress3 = fields(21)
                        Item.ShipAddress4 = fields(22)
                        If fields(23).Contains("GB") Then
                            Item.ShipCountry = "238"
                        Else
                            Item.ShipCountry = ""
                            'CommonFunctions.SendErrorEmail("")
                        End If
                        Item.ShipPostCode = fields(24)
                        Item.PhoneNumber = fields(28)
                        OrderRequest.Items.Add(Item)
Cntr = Cntr + 1
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        'CommonFunctions.SendErrorEmail("")
                        Return False
                    End Try
                End While
                aCSV.OrderRequest = OrderRequest
            End Using
        Next
        Return True
    End Function

                                

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Fernando SotoRetiredCommented:
Hi mehmast;

Then move the first read line just before the while loop and shown below.

Private Function ParseCSVs() As Boolean

    Dim LocalFilePath As String = String.Empty

    For Each aCSV As xCSV In _CSVs
        LocalFilePath = My.Settings.Item("GRFiles") & "DailyOrders\" & aCSV.CSVFileName
    
        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(LocalFilePath)

            MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
            MyReader.Delimiters = New String() {","}  '{vbTab}
            Dim currentRow As String()
            'Loop through all of the fields in the file.  
            'If any lines are corrupt, report an error and continue parsing.  
            Dim OrderRequest As New cCSVOrderRequest
            OrderRequest.Items = New List(Of cCSVProductItem)

            Dim Product As ProductClass = Nothing
            Dim Item As cCSVProductItem = Nothing
            
            '' Read the header row, first line in the file, this is done once per file
            currentRow = MyReader.ReadFields()             
            
            While Not MyReader.EndOfData
                Try

                    ' Include code here to handle the row. 
                    Dim fields As String() = MyReader.ReadFields()
                    Item = New cCSVProductItem()
                    Item.OrderItemNumber = fields(0)
                    Item.PartNumber = fields(2)
                    Item.Description = fields(3)
                    Item.Quantity = fields(4)
                    Item.ShipTitle = fields(17)
                    Item.ShipToName = fields(18)
                    Item.ShipAddress1 = fields(19)
                    Item.ShipAddress2 = fields(20)
                    Item.ShipAddress3 = fields(21)
                    Item.ShipAddress4 = fields(22)
                    If fields(23).Contains("GB") Then
                        Item.ShipCountry = "238"
                    Else
                        Item.ShipCountry = ""
                        'CommonFunctions.SendErrorEmail("")
                    End If
                    Item.ShipPostCode = fields(24)
                    Item.PhoneNumber = fields(28)
                    OrderRequest.Items.Add(Item)
                Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    'CommonFunctions.SendErrorEmail("")
                    Return False
                End Try
            End While
            aCSV.OrderRequest = OrderRequest
        End Using
    Next
    Return True
End Function

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mehmastAuthor Commented:
thank you
0
Fernando SotoRetiredCommented:
Not a problem mehmast, glad to help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.