troubleshooting Question

Ignore empty lines from csv file

Avatar of coperations07
coperations07Flag for United States of America asked on
Visual Basic Classic.NET Programming
13 Comments1 Solution2850 ViewsLast Modified:
Hi,
I'm using VS2010 with VB.Net.

I have a function that reads in a csv file to a datatable. My problem is that the last couple rows in the datatable are blank. I need to ignore these rows.  I've tried checking if the Line Legnth is > 0, but it still brings in. I'm assuming the Legnth check doesn't work b/c there are commas in the line. I've tried checking the value of the first column in the datatable after each line writes to it and then deleting it if it is empty or null but this didn't work either. I would prefer to not write it to the datatable if I can catch it before. Here's what I'm working with...

            Dim sr As New StreamReader(path)
            sr.ReadLine() 'skip the header line
            Dim sFileData As String = sr.ReadToEnd()
            sr.Close()
            sr.Dispose()

            Dim sLines As String() = sFileData.Split(ControlChars.Lf)
            Dim dtRecs As New DataTable()
            Dim sArray As String() = sLines(0).Split(","c)

            For Each s As String In sArray
                dtRecs.Columns.Add(New DataColumn())
            Next

            Dim row As DataRow
            Dim sLastLine As String = ""
            For Each ss As String In sLines
                If ss.Length > 0 Then
                    row = dtRecs.NewRow()
                    sLastLine = ss.Replace(Convert.ToString(ControlChars.Cr), "")
                    row.ItemArray = sLastLine.Split(","c)
                    dtRecs.Rows.Add(row)
                End If
            Next
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 13 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 13 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros