Tony Tony - 5 months ago 42
Vb.net Question

vb.net 2013 - removing blank lines with streamreader

I am using this code snippet (found on here) to read a csv file into an array.

sFile = "c:\test.txt"
Dim sData() As String
Dim arrName, arrValue as New List(Of String)()

Using sr As New StreamReader(sFile)
While Not sr.EndOfStream
sData = sr.ReadLine().Split(","c)

arrName.Add(sData(0).Trim())
arrValue.Add(sData(1).Trim())
End While
End Using


My source file contains 2 - 3 blank lines at the end of the file.
Despite using Trim() - I am still getting these blank lines inserted into the array, and this is causing the rest of my code to fail.

I have verified that it works by deleting the blank lines.

I have tried various techniques found on here and on MSDN but I just can't seem to get rid of these blank lines.

Can anyone help please?

Thanks.

Answer

You could read the line into a separate variable and check if that is empty before parsing the data:

Using sr As New StreamReader(sFile)
    While Not sr.EndOfStream
        Dim sLine As String = sr.ReadLine()
        If Not String.IsNullOrWhiteSpace(sLine) Then
            sData = sLine.Split(","c)

            arrName.Add(sData(0).Trim())
            arrValue.Add(sData(1).Trim())
        End If
    End While
End Using

You may also want to add further validity checks (e.g. if there is no comma, sData(1) will throw an exception, and what if there are multiple commas?).