David Tunnell
David Tunnell

Reputation: 7532

Loading file into array using streamreader

I'm trying to get a file and iterate through it using StreamReader and load each line into an array. I know the file is coming in correctly and it is a text file of data coming in lines.

    Dim req As WebRequest = WebRequest.Create("http://www.blahahahaha.com/data/myfile.csv")
    Dim res As WebResponse = req.GetResponse()
    Dim stream As Stream = res.GetResponseStream()

    Dim lines2 As String()
    Using r As StreamReader = New StreamReader(stream, Encoding.ASCII)
        Dim line As String
        line = r.ReadLine
        Do While (Not line Is Nothing)
            lines2(lineCount2) = r.ReadLine
            lineCount2 += 1
        Loop
    End Using

But the resulting array is empty. What am I doing wrong and how do I fix it?

Upvotes: 2

Views: 3718

Answers (2)

This line:

Dim lines2 As String()

Just declares that lines2 will be a string array. The array itself is not intialized:

Dim lines2(9) As String     ' THIS one has elements

But since you likely do not know how many lines there will be, use a List:

Dim Lines As New List(Of String)

Using r As StreamReader = New StreamReader(Stream, Encoding.ASCII)
    Dim line As String
    line = r.ReadLine
    Do Until String.IsNullOrEmpty(line)
        Lines.Add(line)
        line = r.ReadLine
    Loop
End Using

If the calling code really needs an array:

Return Lines.ToArray()

Upvotes: 4

Karen Payne
Karen Payne

Reputation: 5117

This will return 6 lines as a string array, first line is column names

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim csvAddress As String =
        "https://download.microsoft.com/download/4/C/8/4C830C0C-101F-4BF2-8FCB-32D9A8BA906A/Import_User_Sample_en.csv"

    Dim Lines As String() = GetCsvData(csvAddress)
    For Each line As String In Lines
        Console.WriteLine(line)
    Next
End Sub
Public Function GetCsvData(ByVal csvAddress As String) As String()
    Dim request As WebRequest = WebRequest.Create(csvAddress)
    request.Credentials = CredentialCache.DefaultCredentials
    Dim response As WebResponse = request.GetResponse()

    Dim dataStream As Stream = response.GetResponseStream()
    Dim LineList As New List(Of String)

    Using r As StreamReader = New StreamReader(dataStream, Encoding.ASCII)
        Dim currentLine As String = r.ReadLine
        Do While (Not String.IsNullOrWhiteSpace(currentLine))
            LineList.Add(currentLine)
            currentLine = r.ReadLine
        Loop
    End Using

    Return LineList.ToArray

End Function

Upvotes: 1

Related Questions